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

How to Retrieve GET Parameters in JavaScript?

Mary-Kate Olsen
Release: 2024-12-14 04:08:11
Original
186 people have browsed it

How to Retrieve GET Parameters in JavaScript?

Retrieving GET Parameters in JavaScript

This question addresses the retrieval of GET parameters within JavaScript. Consider the following URL:

http://example.com/page.html?returnurl=/admin

How can JavaScript code within page.html access the GET parameters? For the given example, the func('returnurl') function should return "/admin".

Solution Using window.location

The window.location object provides a way to retrieve GET parameters without the question mark. The following code will do the trick:

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

Enhanced Solution

The provided solution offers a function, findGetParameter(), which takes a parameter name and returns its corresponding value:

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

Alternative Solution with For Loop

An alternative solution using a plain for loop is also provided for compatibility with older browsers (e.g., IE8):

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    var items = location.search.substr(1).split("&amp;");
    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
Copy after login

The above is the detailed content of How to 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