Home  >  Article  >  Web Front-end  >  Detailed explanation of js method of obtaining url parameter value

Detailed explanation of js method of obtaining url parameter value

coldplay.xixi
coldplay.xixiforward
2020-06-12 18:09:543323browse

Detailed explanation of js method of obtaining url parameter value

js method of getting url parameter value

The Location object is a part of the Window object and can be accessed through window. location attribute to access.

hash: Sets or returns the URL (anchor) starting with the pound sign (#).

host: Set or return the host name and port number of the current URL.

hostname: Set or return the host name of the current URL.

href: Set or return the complete URL.

pathname: Set or return the path part of the current URL.

port: Set or return the port number of the current URL.

protocol: Set or return the protocol of the current URL.

search: Sets or returns the URL (query part) starting with a question mark (?).

How js gets the url parameter value

One parameter:

var test =window.location.href;
var 参数=test.split("?参数=")[1];

Multiple parameters:

Method 1:

function GetQueryString(name) { 
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
  var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
  var context = ""; 
  if (r != null) 
     context = r[2]; 
  reg = null; 
  r = null; 
  return context == null || context == "" || context == "undefined" ? "" : context; 
}

Call Method:

var 参数1 = GetQueryString['参数1'];
var 参数2 = GetQueryString['参数2'];
var 参数3 = GetQueryString['参数3'];

Method 2:

function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}

Calling method:

var Request = new Object();
Request = GetRequest();
var 参数1,参数2,参数3,参数N;
参数1 = Request[&#39;参数1&#39;];
参数2 = Request[&#39;参数2&#39;];
参数3 = Request[&#39;参数3&#39;];
参数N = Request[&#39;参数N&#39;];

Recommended tutorial: "JS Tutorial"

The above is the detailed content of Detailed explanation of js method of obtaining url parameter value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:liqingbo.cn. If there is any infringement, please contact admin@php.cn delete
Previous article:What is Ajax used for?Next article:What is Ajax used for?