Home > Web Front-end > JS Tutorial > body text

How to Get Query Parameter Values from a URL Using jQuery?

Susan Sarandon
Release: 2024-11-24 21:11:14
Original
931 people have browsed it

How to Get Query Parameter Values from a URL Using jQuery?

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);
Copy after login

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;
}
Copy after login

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"
}
Copy after login

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"];
Copy after login

Finally, you can use the extracted parameter value in your jQuery statement as follows:

var thequerystring = locationValue;

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

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template