jquery získať querystring z adresy URL

Mám nasledujúcu adresu URL:

http://www.mysite.co.uk/?location=mylocation1

Potrebujem získať hodnotu location z adresy URL do premennej a potom ju použiť v kóde jQuery:

var thequerystring = "getthequerystringhere"

$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);

Vie niekto, ako získať túto hodnotu pomocou JavaScriptu alebo jQuery?

Riešenie

Z: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

To je to, čo potrebujete :)

Nasledujúci kód vráti objekt JavaScript obsahujúci parametre adresy URL:

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Napríklad, ak máte adresu URL:

http://www.example.com/?me=myValue&name2=SomeOtherValue

Tento kód vráti:

{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}

a môžete urobiť:

var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];
Komentáre (12)

Jednoduchý spôsob, ako to urobiť pomocou jQuery a priameho JS, stačí zobraziť konzolu v prehliadači Chrome alebo Firefox, aby ste videli výstup...

  var queries = {};
  $.each(document.location.search.substr(1).split('&'),function(c,q){
    var i = q.split('=');
    queries[i[0].toString()] = i[1].toString();
  });
  console.log(queries);
Komentáre (6)

Pozrite sa na túto odpoveď stackoverflow.

 function getParameterByName(name, url) {
     if (!url) url = window.location.href;
     name = name.replace(/[\[\]]/g, "\\$&");
     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
         results = regex.exec(url);
     if (!results) return null;
     if (!results[2]) return '';
     return decodeURIComponent(results[2].replace(/\+/g, " "));
 }

Metódu môžete použiť na animáciu:

t. j:

var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
Komentáre (0)