I have two HTML pages. I am trying to send parameters to the second URL from the first URL using window.location.href
The code I have tried is:
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>
I don't get any alerts, though the URL formed is correct. what may be the issue with the code?
I just tried your code and it was almost working. You forgot a }
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
}
Now it is alerting: A: me and B: here .
Here is the working code.
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]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.