Home  >  Article  >  Web Front-end  >  How to get request parameters in javascript

How to get request parameters in javascript

藏色散人
藏色散人Original
2021-06-21 11:26:0424212browse

Javascript method of obtaining request parameters: 1. Obtain the URL of the browser through JavaScript; 2. Obtain the value of a certain parameter in the url through Javascript; 3. Extend a method for jQuery to obtain the url parameters through jquery. .

How to get request parameters in javascript

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

How to get request parameters in javascript?

JavaScript obtains the request parameter value in the get method

1. Implementation of obtaining the browser URL through JavaScript

window.location.href

In fact, it only uses the basic window of JavaScript object.

2. Get the value of a certain parameter in the url through Javascript.

function getUrlParam(name) {
//构造一个含有目标参数的正则表达式对象
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
//匹配目标参数
var r = window.location.search.substr(1).match(reg);
//返回参数值
if(r != null) {
return decodeURI(r[2]);
}
return null;
}

You can get the value of the parameter by passing the parameter name in the url through this function. For example, the url is

http://127.0.0.1:8020/JavaScriptFunction/index.html?bb=1&aa='张三'

If we want to get the values ​​​​of bb and aa, we can write like this:

var bb = getUrlParam('bb');
var aa = getUrlParam('aa')

3. We can use this method to extend a method for jQuery to get the url parameters through jquery. The following code is extended for jquery. A getUrlParam() method

(function($) {
$.getUrlParam = function(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r != null) return decodeURI(r[2]);
return null;
}
})(jQuery);

4. Regarding the obtained parameters to prevent Chinese garbled characters

When passing parameters, it is found that encodeURI is used to encode Chinese characters, so the above method is Using decodeURI when parsing parameter encoding ensures that Javascript has a consistent encoding and decoding method for parameters, thus preventing Chinese garbled characters.

In JavaScript, there are two commonly used encoding and decoding functions,

   encodeURI()   decodeURI() 
    encodeURIComponent()    decodeURIComponent()

[Recommended learning: javascript advanced tutorial]

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