1

Good morning!

I need to create an URL that contains a variable with many values (array) and also need a JavaScript code that can read those values and store in memory. Example:

http://(...).html?variable=value1|value2|value3

Can someone help me?

Thanks!

3 Answers 3

1

How about some thing like this:

url could be: .html?variable=value1,value2,value3

function getUrlParameter(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if( results == null ) {
        return "";
    } else {
        return results[1];
    }
}
var res = getUrlParameter("variable").split(",");
alert(res[0]);
alert(res[1]);
alert(res[2]);
Sign up to request clarification or add additional context in comments.

Comments

1

Put the values in the querystring

function AddValues(someValue) {
        var sep = (window.location.href.indexOf("?") === -1) ? "?" : "&";
        window.location.href = window.location.href + sep + "foo=" + someValue;
    }
    function AddArrayValues() {
    var someValues = ['do', 're', 'mi', 'so', 'la', 'ti', 'do']
        var sep = (window.location.href.indexOf("?") === -1) ? "?" : "&";
        window.location.href = window.location.href + sep + "fooArray=" + someValues;
    }

<input type="button" onclick="AddValues('someValue')" value="Add Value"/>
<input type="button" onclick="AddArrayValues()" value="Add Values" />

Get values from queryString

function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[1]);
            vars[hash[0]] = hash[1];
        }

        alert(vars); 
    }

Comments

1

Conventional querystring structure assigns multiple values to a single key:

http://(...).html?variable=value1&variable=value2&variable=value3

Then common JS libraries like dojo.queryToObject can decode it into:

{
  variable: ['value1', 'value2', 'value3']
}  

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.