How to Extract Query Parameters from URL Using jQuery
Question:
How do you obtain the value of a query parameter from a URL using jQuery and use it in your code? For instance, if the URL is http://www.mysite.co.uk/?location=mylocation1, how do you assign the "mylocation1" value to a variable for use in the following jQuery statement:
var thequerystring = "getthequerystringhere" $('html,body').animate({scrollTop: $(""div#" + thequerystring).offset().top}, 500);
Answer:
To extract query parameters from a URL, you can use the following code snippet:
// 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; }
This function takes the URL parameters from the browser's address bar, splits them into key-value pairs, and returns them as an object. For example, the URL http://www.example.com/?me=myValue&name2=SomeOtherValue would return the following object:
{ "me" : "myValue", "name2" : "SomeOtherValue" }
With this function, you can access the query parameters by their keys. In your case, to obtain the "location" parameter, you can write:
var locationValue = getUrlVars()["location"];
Finally, you can use the extracted parameter value in your jQuery statement as follows:
var thequerystring = locationValue; $('html,body').animate({scrollTop: $(""div#" + thequerystring).offset().top}, 500);
The above is the detailed content of How to Get Query Parameter Values from a URL Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!