JavaScript implements the method of passing values between pages

  • 2020-05-27 04:14:40
  • OfStack

This article demonstrates an example of how JavaScript can be used to transfer values between pages. Share with you for your reference. The details are as follows:

The questions are as follows:

On the a.html page, < form > The onsubmit event calls a method foo() that opens the b.html page and passes parameters to b.html. The method foo() needs to pass variable parameters to the b.html page, and accepts parameter values on the b.html page, but cannot use server-side techniques.

The solution code is as follows:

The a.html page is as follows:


<html>
<head>
  <title> demo </title>
  <meta name="Author" content="xugang" />
  <script type="text/javascript">
  function foo(){
   var a ="abc"; // a For a variable's value 
   var str = "b.html?id="+a+";";
   //alert(document.frm.action);
   // plan 1 (void) 
   // document.frm.action = str;
   // plan 2 (void) 
   // window.location.href = str;
   // plan 3 (effective) 
   window.location.replace(str);
   return false;
  }
 </script>
</head>
<body>
   <FORM name="frm" method="get" 
   onsubmit = "return foo()" >
      <INPUT TYPE="SUBMIT" />
   </FORM>
</body>
</html>

Note: the b.html page must exist in advance.

The code to obtain the parameter value of b.html is as follows:

b.html part of the code


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

Supplement:

myjs. js code:


function foo(){ 
    var str = "abc"; 
    //document.forms[0].hid.value = str; 
    var frm = window.event.srcElement; 
    frm.hid.value = str; 
    return true; 
}

a. html code:


<html> 
<head> 
 <title> demo </title> 
 <meta name="Author" content="xugang" /> 
 <script src="myjs.js"></script> 
</head> 
<body> 
 <FORM name="frm" METHOD="get" ACTION="b.html" 
 onsubmit="return foo()"> 
  <INPUT TYPE="hidden" id="hid" name="hid"> 
  <INPUT TYPE="submit" value=" submit "> 
 </FORM> 
</body> 
</html>

Note: when passing a value to an b.html page, the b.html page must already exist!

b. html code:


<HTML> 
 <HEAD> 
  <TITLE> New Document </TITLE> 
 </HEAD> 
 <BODY> 
  <SCRIPT LANGUAGE="JavaScript"> 
   document.write(decodeURIComponent(location.search.substr(3)));
  </SCRIPT> 
 </BODY> 
</HTML>

Hope that this article described the javascript programming help.


Related articles: