JS实现页面间传值

1.location.href方法
参数传出页面Post.html
function Post(){
    //多参值 Read.html?username=baobao&sex=male;
    url="Read.html?username="+escape(document.all.username.value);
    url+="&sex="+escape(document.all.sex.value);
    location.href=url;
}
参数接收页面Read.html
var url = location.search;
var Request = new Object();
if(url.indexOf("?")!=-1){
    var str = url.substr(1)//去除?号
    strs = str.sqlit("&");
    for(var i = 0;i<strs.length;i++){
        Request[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
    }
}
alert(Request["username"]);
alert(request["sex"]);
//---------------------------------------------------------
1.接收参数:
(1)接收参数函数封装
function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}
(1)调用
var a=GetRequest();
var index_1=a['id'];
优点:取值方便.可以跨域.
缺点:值长度有限制

2.JavaScript静态页面值传递之Cookie篇
*---------------setCookie(name,value) -----------------
*setCookie(name,value)
* 功能:设置得变量name的值
* 参数:name,字符串;value,字符串.
* 实例:setCookie('username','baobao')
*---------------setCookie(name,value) -----------------
function setCookie(name,value)
{
    var Days = 30; //此 cookie 将被保存 30 天
  var exp = new Date();
  exp.setTime(exp.getTime() +Days*24*60*60*1000);
  document.cookie = name +"="+ escape (value) + ";expires=" + exp.toGMTString();
  location.href = "Read.html";//接收页面.
}
/*
*---------------get Cookie(name) -----------------
*getCookie(name)
* 功能:取得变量name的值
* 参数:name,字符串.
* 实例:alert(getCookie("baobao"));
*---------------get Cookie(name) -----------------
*/
function getCookie(name){
    var arr = document.cookie.match(new RegExp("(^|)"+name+)=([^;]*)(;|$));
    if(arr!=null){
        return unescape(arr[2]);
    }
    else{
        return null;
    }
}
页面引用alert(getCookie("baobao"));
优点:可以在同源内的任意网页内访问.生命期可以设置.
缺点:值长度有限制.

3.JavaScript静态页面值传递之Window.open篇
这两窗口之间存在着关系.父窗口parent.htm打开子窗口son.htm
子窗口可以通过window.opener指向父窗口.这样可以访问父窗口的对象.
<input type=text name=maintext>//设置为父窗口
<input type=button value="Open">
Read.htm
<scriptlanguage="javascript" >
    //window.open打开的窗口.
    //利用opener指向父窗口.
    var parentText = window.opener.document.all.maintext.value;
    alert(parentText);
</script>
优点:取值方便.只要window.opener指向父窗口,就可以访问所有对象.不仅可以访问值,还可以访问父窗口的方法.值长度无限制.
缺点:两窗口要存在着关系.就是利用window.open打开的窗口.不能跨域.




posted @ 2017-06-19 10:01  liujun421  阅读(1605)  评论(0编辑  收藏  举报