Young87

当前位置:首页 >个人收藏

如何利用JavaScript 在页面间传值

本文转载自: https://www.cnblogs.com/xugang/archive/2010/07/22/1783239.html 作者:xugang 转载请注明该声明。

 

问题场景如下:

在 a.html 页面中,<form> 的 onsubmit 事件调用一个方法 foo( ),打开 b.html 页面的同时给 b.html 传递参数。方法 foo( ) 中需要传递变量参数到 b.html 页面,在 b.html 页面接受参数值,但不能使用服务器端技术。

 

解决代码如下:

961ddebeb323a10fe0623af514929fc1.jpe a.html
< html >
< head >
   
< title >  demo  </ title >
   
< meta  name ="Author"  content ="xugang"   />
   
< script  type ="text/javascript" >
    
function  foo(){

     
var  a  = " abc " //  a为变量值
      var  str  =   " b.html?id= " + a + " ; " ;

     
// alert(document.frm.action);

     
// 方案一(无效)
      //  document.frm.action = str;

     
// 方案二(无效)
      //  window.location.href = str;

     
// 方案三(有效)
     window.location.replace(str);
     
return   false ;
   }
  
</ script >
</ head >
< body >
     
< FORM   name ="frm"   method ="get"   onsubmit  = "return foo()"   >
           
< INPUT   TYPE ="SUBMIT" />
     
</ FORM >
</ body >
</ html >

 

注意:必须 b.html 页面事先存在即可。

b.html 获得参数值的代码如下:

961ddebeb323a10fe0623af514929fc1.jpe b.html 部分代码
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   "" ;
}

 

 

补记:

================================================================================================

今天一早起来,居然从睡梦中找到了更好的解决办法。

看来睡觉是灵感之源,呵呵 ^_^

 

myjs.js 代码:

961ddebeb323a10fe0623af514929fc1.jpe myjs.js代码
function  foo(){ 
  
        
var  str  =   " abc "
        
// document.forms[0].hid.value = str; 
  
        
var  frm  =  window.event.srcElement; 
        frm.hid.value 
=  str; 
        
return   true
 }

 

a.html 代码:

961ddebeb323a10fe0623af514929fc1.jpe a.html
< 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 ="提交" >  
  
</ FORM >  
</ body >  
</ html >

 

注意:给 b.html 页面传值时,b.html 页面必须事先已存在!

b.html 代码:

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

 

除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog

上一篇: System.Data.SqlClient.SqlException: 将截断字符串或二进制数据。语句已终止

下一篇: Spring启动异常: cvc-elt.1: Cannot find the declaration of element 'beans'(转)

精华推荐