问题: 项目中,在页面之间点击跳转时需要进行参数传递,需要将中文的参数放入到url中进行跳转传参。
初期简陋想法:通过在li中直接进行点击跳转传参,将参数(数值及中文字符串)进行传递。
注:全部为ajax获取后进行动态添加到html中
相关代码如下:
<li onclick='send(" + data[i].id +",'"+data[i].name+ "')'>" + data[i].name + "</li>"
function typecontent(id,name) {
window.location.href = "xxxxx.html?id=" + id + "$name="+name;
}
结果:直接报错,相关中文字符串提示为undefined,此处错误原因未知。已抛弃!
———————————————分割线—————————————————————
后期:查阅资料后,在js中进行传参,由于包含中文,所以需要经过两次encodeURI()编码和两次decodeURI()解码
<li class='goods' data-id='"+data[i].id+"'>" + data[i].name + "</li>"
使用encodeURI()编码时,点击事件传参
$(".list").on("tap","li",function(){
var _this=this;
var id=$(_this).attr("data-id");
var name=$(_this).text();
if($(_this).text()!=""){
var url=encodeURI("xxxxxxx.html?id"+id+"&name"+name);
var enurl = encodeURI(url);
window.location.href =enurl;
}
})
接受参数的页面:
URL解析函数如下
function GetRequest() {
var url =decodeURI(decodeURI(location.search)); //获取url中"?"符后的字串,使用两次decodeRUI解码
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
return theRequest;
}
}
使用方法
var postData = GetRequest();
console.log(postData);
输出为json格式对象,可直接使用,如postData.id,postData.name;