jquery ottiene una querystring dall'URL

Ho il seguente URL:

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

Quello che mi serve è ottenere il valore di location dall'URL in una variabile e poi usarlo in un codice jQuery:

var thequerystring = "getthequerystringhere"

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

Qualcuno sa come prendere quel valore usando JavaScript o jQuery?

Soluzione

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

Questo è quello che ti serve :)

Il seguente codice restituirà un oggetto JavaScript contenente i parametri dell'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;
}

Per esempio, se avete l'URL:

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

Questo codice restituirà:

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

e si può fare:

var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];
Commentari (12)

Un modo semplice per farlo con un po' di jQuery e JS diretto, basta visualizzare la tua console in Chrome o Firefox per vedere l'output...

  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);
Commentari (6)

Date un'occhiata a questo risposta di 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, " "));
 }

Puoi usare il metodo per animare:

ie:

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