Home>Article>Web Front-end> How to get URL parameters using JavaScript

How to get URL parameters using JavaScript

不言
不言 Original
2018-11-30 10:37:03 3087browse

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.

How to get URL parameters using JavaScript

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.

How to get URL parameters using JavaScript

Add parameter "q" to the end of the URL. (?q=testabc is added to the end of the URL.)

How to get URL parameters using JavaScript

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!

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