我使用 cookies 和查询字符串将数据从一个页面传递到另一个页面。这是我的代码,单击按钮时我成功地对 URL 字符串进行了编码。
$('#editListButton').click(function(){
var orderCookie = getCookie('ordercookie');
var cookieArray = JSON.parse(orderCookie);
for (i = 0; i < cookieArray.length; i++) {
urlString += cookieArray[i].toString();
}
window.location.href = "http://localhost:8888/abc.php?action=remove&value&=" +
encodeURIComponent(urlString); //cookie value
});
在另一页上,我正在尝试解码此网址,我需要数组中的分隔项目。数组的元素应该是;
数组[0] = 6.25usd%20-%201%20Unit%20%20Ta%20Ft%20ItemA%20ItemB
数组[1] = 13usd%20-%202%20Unit%20Fiesta
下面的代码仅针对第一个元素正确运行,实际上,无论我做什么,我都无法生成数组。它将整个 url 作为唯一的元素。我需要一种方法来拆分此 url 以将项目放入数组中。
<script>
var action = /(?:\?|&)action=([^&$]+)/.exec(location.search);
if ('remove' === action[1]) {
var value = /(?:\?|&)value&=([^&$]+)/.exec(location.search);
$('#defaultText').remove();
for (i = 1; i < value.length; i++) {
alert(value[i]);
$('#orderList').append('<p>' + value[i].toString().replace(/%20/g, " ") + '</p>' + '<br>');
}
}
</script>
最佳答案
这段代码解决了我的问题。
var url = location.toString();
var res = decodeURIComponent(url.split(/\?|=/).slice(-1));
var idx = [];
var arr = [];
var i = 0;
var z = 0;
do {
z = res.indexOf("," ,z+1);
if (z > -1){
idx[i] = z;
i++;
}
} while (z > -1)
for (i = 0; i < idx.length; i++){
if(i === 0){
arr.push(res.slice(0, idx[i]));
} else {
arr.push(res.slice(idx[i-1]+1, idx[i]));
}
}
$('#defaultText').remove();
for (i = 0; i < arr.length; i++) {
$('#orderList').append('<p>' + arr[i].toString() + '</p>');
}
关于javascript - 如何在 JavaScript 中拆分数组的查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29323241/