1. 程式人生 > >jqueryURL中引數中解決中文亂碼問題的兩種方法

jqueryURL中引數中解決中文亂碼問題的兩種方法

一、正則分析法

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);  //獲取url中"?"符後的字串並正則匹配            
    var context = "";             
    if (r != null)
        context = r[2];             
	reg = null;             
	r = null; 
    return context == null || context == "" || context == "undefined" ? "" : context;         
}     

呼叫方法:

alert(GetQueryString("引數名1")); 

二、

function GetRequest() { 
var url = location.search; //獲取url中"?"符後的字串 
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 Request = new Object(); 
Request = GetRequest(); 
var 引數1,引數2; 
引數1 = Request['引數1']; 

引數2 = Request['引數2'];

如果引數中含有中文字元,注意轉編碼和解碼: 

1、傳參頁面

location.href = "${ctx}/web/resourceList?u=admin&keyword=" + encodeURI($("#keyword").val());

2、接收引數頁面

decodeURI(GetQueryString("keyword"))