Javascript gets the parameters passed in the Address bar (URL)

Source: Internet
Author: User
Tags url example

Sometimes we need to use the URL in the JS file parameters, but JavaScript is the client execution of the scripting language, and the session is the server side of the object, we can not directly get the value in the session. So, how do we get the parameters in the URL in the JS file? Here are two ways, one is the string splitting method, the other is the regular matching method. The first: String splitting method This method obtains the parameter part of the URL through the Location.search method, and then further processes the resulting. The specific code is as follows: [JavaScript]//get parameters passed in the Address bar (URL)function Getrequest () {//URL Example: xxx.aspx?id= "+ ID +" &name= "+ Name;    varurl = location.search;//gets the URL in the "?" characters and subsequent strings.    varTherequest =NewObject (); if(Url.indexof ("?") != -1)//There is a question mark in the URL, and it says there are parameters.     {         varstr = URL.SUBSTR (1); STRs= Str.split ("&");  for(vari =0; i < strs.length; i + +) {Therequest[strs[i].split ("=")[0]]=unescape (Strs[i].split ("=")[1]); }      }      returntherequest; Calling function code: [JavaScript]varRequest =NewObject (); //get the parameters in the URLRequest=getrequest (); varID, Name;//ID, nameID= request['ID'];//IDName= request['Name'];//nameThe second: regular matching method This method in fact the principle and the previous method is similar, are extracted from the URL, only the method of extraction is different. [JavaScript] function getquerystring (name) {varReg =NewREGEXP ("(^|&)"+ name +"= ([^&]*) (&|$)"); varR = Window.location.search.substr (1). Match (REG); if(r! =NULL) {           returnUnescape (r[2]); }      return NULL; Calling code: [JavaScript]varID; ID= GetQueryString ("ID");  These are the two methods of getting the parameters in the URL in JavaScript. 

Javascript gets the parameters passed in the Address bar (URL)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.