Reputation: 1
Say I have a simple HTML document with the following:
<a href="results.html"> cake </a>
<a href="results.html"> pie </a>
and results.html
contains a variable that needs to be declared in Javscript as 100 for the first link, 200 for the second, and so on.
Is there any way I can make it so that when you click on the first link, it opens results.html
with a javascript variable set to cake, the second one opens results.html
with the variable set to pie, and so on?
Upvotes: 0
Views: 56
Reputation: 77956
<a href="results.html?keyword=cake"> cake </a>
<a href="results.html?keyword=pie"> pie </a>
In results.html :
<script type="text/javascript">
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var query = getQueryParams(document.location.search);
alert(query.keyword);
</script>
Upvotes: 0
Reputation: 32713
You can pass them in the query string. For example:
<a href="results.html?result=cake"> cake </a>
<a href="results.html?result=pie"> pie </a>
In your results.html page you get and parse the query string. For example:
var queryStr = window.location.search.substring(1);
var params = parseQueryStr(queryStr);
console.log(params["result"]);
var parseQueryStr = function(queryStr) {
var params = {};
var queryArray = queryStr.split("&");
for (var i = 0, var l = queryArray.length; i < l; i++ ) {
var temp = queryArray[i].split('=');
params[temp[0]] = temp[1];
}
return params;
};
Upvotes: 2