This article mainly introduces how to obtain URL parameters in a centralized manner using Js + Jq. For more information, see the JQ value method:
Jquery itself does not have a method to get URL parameters, but there is already a plug-in, you can directly get URL and other parameters
Plug-in connection home: https://github.com/allmarkedup/jQuery-URL-Parser
Download link: http://download.github.com/allmarkedup-jQuery-URL-Parser-bb2bf37.zip
Examples of use
Using the current page's url (for these examples https://mysite.com/information/about/index.html? ItemID = 2 & user = dave ):
// Get the protocol
JQuery. url. attr ("protocol") // returns 'http'
// Get the path
JQuery. url. attr ("path") // returns '/information/about/index.html'
// Get the host
JQuery. url. attr ("host") // returns 'mysite. com'
// Get the value for the itemID query parameter
JQuery. url. param ("itemID") // returns 2
// Get the second segment from the url path
JQuery. url. segment (2) // returns 'about'
Using a different url to the current page:
// Set a different URL and return the anchor string
JQuery. url. setUrl ("http://allmarkedup.com/category/javascript/#footer"). attr ("anchor") // returns 'footer'
JS native acquisition:
The most primitive JS method:
The Code is as follows:
Var URLParams = new Array ();
Var aParams = document. location. search. substr (1). split ('&');
For (I = 0; I <aParams. length; I ++ ){
Var aParam = aParams [I]. split ('= ');
URLParams [aParam [0] = aParam [1];
}
Call this method as follows:
Http: // 127.0.0.1/index. php? Name = name1 & cid = 123
// Obtain the passed name parameter
Name = URLParams ["name"];
Document. write (name );
// Obtain the passed cid
Cid = URLParams ["cid"];
Regular Expression Analysis:
Method 1:
The Code is as follows:
Function getQueryString (name ){
Var reg = new RegExp ("(^ | &)" + name + "= ([^ &] *) (& | $)", "I ");
Var r = window. location. search. substr (1). match (reg );
If (r! = Null) return unescape (r [2]); return null;
}
Call this method as follows:
The Code is as follows:
Alert (GetQueryString ("parameter name 1 "));
Alert (GetQueryString ("parameter name 2 "));
Alert (GetQueryString ("parameter name 3 "));
Method 2:
The Code is as follows:
Call this method as follows:
The Code is as follows: