开发者

Variable with multiple values in URL

开发者 https://www.devze.com 2023-04-11 18:28 出处:网络
Good morning!开发者_如何学Go 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:

Good morning!开发者_如何学Go

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!


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]);


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); 
    }


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']
}  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号