0

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?

2 Answers 2

2

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;
};
Sign up to request clarification or add additional context in comments.

1 Comment

using location.hash would be a lot easier in my opinion... Of course it won't be available on the server-side, but it doesn't look like the OP needs it.
0
<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.