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)
For instance, given the URL:
http://example.com/page.html?returnurl=%2Fadmin
The above code will output:
returnurl=%2Fadmin
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; }
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; }
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!