早上好!
我需要创建一个包含带有许多值(数组)的变量的URL,并且还需要一个可以读取这些值并存储在内存中的JavaScript代码。例如:
http://(...).html?variable=value1|value2|value3
有人可以帮助我吗?
谢谢!
答案 0 :(得分:1)
这样的事情怎么样:
url可能是:.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]);
答案 1 :(得分:1)
将值放在查询字符串
中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" />
从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);
}
答案 2 :(得分:1)
传统querystring structure为单个键分配多个值:
http://(...).html?variable=value1&variable=value2&variable=value3
然后像dojo.queryToObject
这样的常见JS库可以将其解码为:
{
variable: ['value1', 'value2', 'value3']
}