JS 前端頁面之間互傳數據


一、URL 傳參[1]

優點:取值方便.可以跨域。
缺點:值長度有限制。

Location 對象[2]

Location 對象包含有關當前 URL 的信息。
Location 對象是 window 對象的一部分,可通過 window.location.xxx 格式的相關屬性對其進行訪問。

search 屬性是一個可讀可寫的字符串,可設置或返回當前 URL 的查詢部分(問號 ? 之后的部分)。

RegExp 對象[3]

RegExp 對象表示正則表達式。

match 是支持正則表達式的 String 對象的方法,作用是找到一個或多個正則表達式的匹配。

示例

parent

<body>
    <input type="button" value="打開新窗口" onclick="open_param1()">
    <input type="button" value="顯示返回值" onclick="open_param2()">

<script>
    function open_param1(){
        var id = 1;
        window.open("child.html?id=" + id); 
    }
    
    function open_param2(){
        var afterUrl =  window.location.search.substring(1);
        alert(afterUrl);
    }
</script>
</body>

child

<body>
    <input type="button" value="點擊顯示參數" onclick="param()">

    <form id="test1" action="parent.html">
        <input name="name" type="text" value="zhangsan" /> 
        <input name="age" type="text" value="18" /> 
        <input type="submit" value="提交"/>
    </form>

<script>
  function param(){
      var url = location.search;
      var Request = new Object();
      if(url.indexOf("?") != -1){
        var str = url.substr(1) //去掉?號
        strs= str.split("&");
        for(var i = 0; i < strs.length; i++){
           Request[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
      }
      //alert(Request[參數名]);
    console.log(Request);
    // 例一
    console.log("例一")
    console.log(Requests("a"));
    console.log(Requests("b"));
    console.log(Requests("c"));

    //例二
    console.log("例二")
    var str ="www.abc.com/index.htm?a=1a&b=2b&c=3c";
    console.log(str.getQuery("a"));
    console.log(str.getQuery("b"));
    console.log(str.getQuery("c"));
}

// 例一
function Requests(strName){
    var strHref ="www.abc.com/index.htm?a=1a&b=2b&c=3c";
    var intPos = strHref.indexOf("?");
    var strRight = strHref.substr(intPos + 1);
    var arrTmp = strRight.split("&");

    for(var i = 0; i < arrTmp.length; i++){
        var arrTemp = arrTmp[i].split("=");
        if(arrTemp[0].toUpperCase() == strName.toUpperCase())
            return arrTemp[1];
    }
    return "";
}

// 例二
String.prototype.getQuery = function(name){
  var reg = new RegExp("(^|&)"+ name+"=([^&]*)(&|$)");
  var r = this.substr(this.indexOf("?")+1).match(reg);
  if(r!=null) 
        return unescape(r[2]); 
    return null;
}
</script>
</body>

二、Cookie

優點:可以在同源內的任意網頁內訪問。生命期可以設置。
缺點:值長度有限制。

示例

注意:本地直接打開 Cookie 設置可能不成功,起一個服務器試試。

parent

<body>
    <input type="text" id="txt1" name="txt1">
    <input type="button" value="Post" onclick="param()">
<script>
function param() {
    var str = document.getElementById("txt1").value;
    setCookie("str", str);
}
    
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 = "child.html";
}
</script>
</body>

child

<body>

<script>
function getCookie(name){
  var arr = document.cookie.match(new RegExp("(^|)"+name+"=([^;]*)(;|$)"));
  if(arr != null) 
        return unescape(arr[2]); 
    return null;
}
console.log(getCookie("str"));
</script>

三、Window[4]

xxxStorage 屬性

localStorage 和 sessionStorage 屬性允許在瀏覽器中存儲 key/value 對的數據。
localStorage 用於長久保存整個網站的數據,保存的數據沒有過期時間,直到手動去刪除。
localStorage 屬性是只讀的。
sessionStorage 用於臨時保存同一窗口(或標簽頁)的數據,在關閉窗口或標簽頁之后將會刪除這些數據。

// 存
localStorage.setItem("attributeName", "localStorage");
sessionStorage.setItem("attributeName", "sessionStorage");
// 取
localStorage.getItem("attributeName");
sessionStorage.getItem("attributeName");

open() 方法

window.open(URL, name, specs, replace)

使用 window.open 打開的兩個窗口之間存在着關系“父子”關系。
子窗口可以通過 window.opener 指向父窗口,訪問父窗口的對象。

優點:取值方便。
只要 opener 指向父窗口,就可以訪問所有對象。
不僅可以訪問值,還可以訪問父窗口的方法。值長度無限制。

缺點:兩窗口要存在着關系。
就是需要使用 open 打開窗口,不能跨域。

示例

注意:本地直接打開設置可能不成功,起一個服務器試試。

parent

<body>
    <input type="text" id="txtId"/>
    <input type="text" id="txtName"/>
    <input type="button" id="btnShow" onclick="showItem();"  value="show child"/>
<script>
    function showItem() {
        var win = window.open("B.html",null," height=300,width=450,  Left=300px,Top=20px, menubar=no,titlebar=no,scrollbar=no,toolbar=no, status=no,location=no");
    }
</script>
</body>

child

<body>
    <input type="button" id="btnSelect" onclick="check()"  value="test"/> 
<script>
    function check(){
        window.opener.document.getElementById("txtId").value="id";
        window.opener.document.getElementById("txtName").value="name";
    }
</script>
</body>

參考


  1. JS 頁面間傳值 ↩︎

  2. Location 對象 ↩︎

  3. JavaScript RegExp 參考手冊 ↩︎

  4. Window 對象 ↩︎


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM