使用javascript发送和检索url参数

时间:2013-12-11 10:57:25

标签: javascript html

我有两个HTML页面。我正在尝试使用 window.location.href

从第一个网址向第二个网址发送参数

我尝试的代码是:

me1.html

<html>
<head>
</head>
<body onload="redirectPage();">
<script>
    function redirectPage(){
        var a = "me";
        var b = "here";
        var url = "me2.html?a="+String(a)+"&b="+String(b);
        window.location.href = url;
    }
</script>

</body>

</html>

me2.html

<html>
<head></head>
<body onload="getValues();">
<script>
    function getValues(){
        var a,b;
        var SearchString = window.location.search.substring(1);
        var VariableArray = SearchString.split('&');
        for(var i = 0; i < VariableArray.length; i++){
            var KeyValuePair = VariableArray[i].split('=');
            if(KeyValuePair[0] == "a"){
                a = KeyValuePair[1];
                console.log("CUSTOMER KEY: "+a);
                alert("A: "+String(a));
            }
            else if(KeyValuePair[0] == "b"){
                b = KeyValuePair[1];
                console.log("USER KEY: "+String(b));
                alert("B: "+b);
            }

    }
</script>
</body>
</html>

虽然形成的网址是正确的,但我没有收到任何提醒。 这可能是代码的问题?

2 个答案:

答案 0 :(得分:1)

我刚试过你的代码,它几乎正常工作。你忘记了}

function getValues(){
    var a,b;
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
    for(var i = 0; i < VariableArray.length; i++){
        var KeyValuePair = VariableArray[i].split('=');
        if(KeyValuePair[0] == "a"){
            a = KeyValuePair[1];
            console.log("CUSTOMER KEY: "+a);
            alert("A: "+String(a));
        }
        else if(KeyValuePair[0] == "b"){
            b = KeyValuePair[1];
            console.log("USER KEY: "+String(b));
            alert("B: "+b);
        }
    } // you forgot to close the for loop here
}

现在警报: A:我 B:这里

答案 1 :(得分:0)

这是工作代码。

<强> me.html

var a = "me",
    b = "here",
    url = "";

url = "me2.html?a=" + a + "&b=" + b;
window.location.href = url;

<强> me2.html

var url,
    params,
    paramArr,
    keyVal;

url = window.location.href;
params = url.split("?")[1];
paramArr = params.split("&");

for(var i=0; i<paramArr.length; i++){
   keyVal = paramArr[i].split("=");
   alert("Key: " + keyVal[0] + ", Value: " + keyVal[1]);
}