js的url傳遞中文引數亂碼的解決方案
第一部分:html
<input type="button" value="編碼" class="sp-btn-blue" onclick="urlEncode()" />
<input type="button" value="解碼" class="sp-btn-blue" onclick="UrlSearch()" /><label id="showName"></label>
第二:js部分
<script type="text/javascript">
function urlEncode() {
var UserName_New="小網";
var encodename=encodeURI(UserName_New);
console.log(encodename);
window.location.href = "http://localhost:2510/encodeChinese.html?UserName=" + encodename+"&haode=121";
//byte[] UserName_bytes = System.Text.Encoding.UTF8.GetBytes(UserName_New); //將字串轉為bytes
//var UserName = HttpUtility.UrlEncode(UserName_bytes);
}
function getUrl() {
var str = location.href; //取得整個位址列
var num = str.indexOf("?")
str = str.substr(num + 1); //取得所有引數
var loastr = "";
var loc = "";
$.each(str.split('&'), function (index, item) {
item = item.split('=');
var name = item[0];
var val = item[1];
loastr = "\"" + name + "\":\"" + val + "\",";
loc += loastr;
});
loc = loc.substring(0, loc.length - 1);
loc = "{" + loc + "}";
var obj = JSON.parse(loc);//將字元型陣列轉換為物件
return obj;
}
function UrlSearch() {
var geturltext = getUrl(); //得到全部引數
var getName = decodeURI(geturltext.UserName);
//alert(getName);
$("#showName").text("顯示名稱:"+getName);
}
</script>