js页面之间传参方式集合

来源:互联网 发布:编程赚钱的网站 编辑:程序博客网 时间:2024/06/05 20:27

总有一款适合你。。。

如果想了解iframe有关传值请参看之前文章:iframe跨不跨域通讯方式集合;

这篇主要是说说其他几种页面之间传值的实现:

实现一:url传值

这种传值方式就是通过在url后面增加参数,然后打开该url后页面获取参数信息,再用js进行处理。

main.html:

<input id='myText'><button onClick='post()'>

<script>

function post(){

  url= "other.html?name="+escape(document.getElementById('myText').value);

  location.href=url;

}

</script>

other.html:

<script>

var url=location.search,obj={};

if(url.indexOf("?")!=-1){

  var str = url.substr(1)

  strs= varstr.split("&");

  for(var i=0;i<strs.length;i++){

     obj[strs[i].split("=")[0]]=unescape(strs[ i].split("=")[1]);

  }

}

alert(obj.name)

</script>

实现二:cookie传值:

实现思想就是通过document.cookie进行设置值以及取值

main.html

<script>

function setCookie(name,value){

var Days = 30; 

  var exp = new Date();

  exp.setTime(exp.getTime() +Days*24*60*60*1000);

  document.cookie = ""+name +"="+ escape (value) + ";expires=" + exp.toGMTString();

}

setCookie('name','yuchao');

location.href = "other.html";

</script>

other.html:

<script>

function getCookie(name){

var arr =document.cookie.match(new RegExp("(^|)"+name+"=([^;]*)(;|$)"));

  if(arr !=null) return unescape(arr[2]); 

return null;

}

document.getElementById(xx).innerHTML=getCookie('name');

</script>

这里需要注意的是,如果你在静态页面下测试chrome浏览器是无法读取设置cookie的,也就是说如果要实现该传值必须将运行环境放到服务器上。

实现三:showModalDialog方式:

使用方式:

var rtn=window.showModalDialog(url ,arguments,style);

参数说明:

url要新打开的窗口链接,为防止缓存一般都会加上?random="+Math.random()

arguments传递参数内容,参数类型不限,可以是对象数组等,例如{name:xxx}

style打开窗口样式控制,用来控制新窗口外观等信息,可以使用下面一个或几个

 参数名参数介绍dialogHeight对话框高度,不小于100pxdialogWidth对话框宽度dialogLeft离屏幕左的距离dialogTop离屏幕上的距离center{ yes | no | 1 | 0 } :      是否居中,默认yes,但仍可以指定高度和宽度help{yes | no | 1 | 0 }:        是否显示帮助按钮,默认yesresizable{yes | no | 1 | 0 } [IE5+]:是否可被改变大小。默认nostatus{yes | no | 1 | 0 } [IE5+]:是否显示状态栏。默认为yes[ Modeless]或no[Modal]scroll{ yes | no | 1 | 0 | on | off }:是否显示滚动条。默认为yes

接受参数页面调用window.dialogArguments;取得传递参数,

关闭弹出页面后也可以利用window.returnValue进行回传值。

举例如下:

main.html:

<script>

function dialogPost(){

var rtn=window.showModalDialog('other.html' ,{name:'yuchao',sex:'male'} );

document.getElementById('dialag').innerHTML='弹出窗口返回数据为:'+rtn;//返回nihao

}

</script>

other.html:

<button onClick='closeNow()'>

<script>

var obj = window.dialogArguments;

      alert("您传递的name为:" + obj.name)

function closeNow(){

window.returnValue='nihao';

    window.close();

}

</script>

特别说明:利用该方式可以在静态页面下打开一个窗口,但是不能在静态下进行传值,也需要放置服务器上才可。

实现四:postMessage

html5中一种先进的通讯方式 : 详见之前一篇文章
0 0
原创粉丝点击