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

How to Retrieve GET Parameters in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 04:08:11187browse

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)

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;
}

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;
}

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!

Statement:
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