Home > Web Front-end > JS Tutorial > How to Access and Retrieve GET Parameters in JavaScript?

How to Access and Retrieve GET Parameters in JavaScript?

Patricia Arquette
Release: 2024-12-15 17:22:10
Original
203 people have browsed it

How to Access and Retrieve GET Parameters in JavaScript?

Accessing GET Parameters in JavaScript

Retrieving GET parameters within an HTML page's JavaScript can be achieved using the window.location object. To obtain the GET parameters without the question mark, utilize the following code:

window.location.search.substr(1)
Copy after login

For instance, given the URL:

http://example.com/page.html?returnurl=%2Fadmin
Copy after login

The above code will output:

returnurl=%2Fadmin
Copy after login

Alternative Method with Function

To create a function that retrieves specific GET parameters, use:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    location.search
        .substr(1)
        .split("&")
        .forEach(function (item) {
            tmp = item.split("=");
            if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
        });
    return result;
}
Copy after login

Calling the function with findGetParameter('returnurl') will return "/admin."

Plain For Loop Variation

For compatibility with older browsers such as IE8, use a plain for loop:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    var items = location.search.substr(1).split("&");
    for (var index = 0; index < items.length; index++) {
        tmp = items[index].split("=");
        if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
    }
    return result;
}
Copy after login

The above is the detailed content of How to Access and Retrieve GET Parameters in JavaScript?. 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