Home>Article>Web Front-end> How to get URL parameters using JavaScript
If you wish to get and use URL parameters via JavaScript. In JavaScript, you can use "document.location.search" to get the parameters of the URL. However, since you can only retrieve the parameter's string immediately after the URL path, the fetched string must be parsed to get the value of each parameter.
Let’s look directly at the example
The code is as follows
GetParam.html
这是一个参数
Note:
The string in the URL parameter part can be obtained through the "document.location.search" attribute. Get the second and subsequent strings by calling the substring(1) method. (If the URL parameter is "?Q=ABCD&m=30", then "q=ABCD&m=30" will be obtained.)
Subsequently, the obtained string is split by "&". If the obtained string is "q=ABCD&m=30", then q=ABCD is assigned to parameter[0] and m=30 is assigned to parameter[1].
In addition, the individual elements of the parameter are separated by '=', the value and parameter name are obtained, stored in the result associative array and returned as the return value.
function GetQueryString() { if (1 < document.location.search.length) { var query = document.location.search.substring(1); var parameters = query.split('&'); var result = new Object(); for (var i = 0; i < parameters.length; i++) { var element = parameters[i].split('='); var paramName = decodeURIComponent(element[0]); var paramValue = decodeURIComponent(element[1]); result[paramName] = decodeURIComponent(paramValue); } return result; } return null;}
Run results
Executing the HTML file will display the following effect on the browser.
Add parameter "q" to the end of the URL. (?q=testabc is added to the end of the URL.)
can get the parameters and output the obtained parameter "testabc" on the page.
The above is the detailed content of How to get URL parameters using JavaScript. For more information, please follow other related articles on the PHP Chinese website!