場景:
使用jQuery的ajax方法提交ajax請求,代碼如下:
1$.ajax({
2 dataType : 'json'
3 ,type : 'POST'
4 ,url : 'http://localhost/test/test.do'
5 ,data : {id: 1, type: '商品'}
6 ,success : function(data){
7
8 }
9});
問題:
提交后后臺(tái)action程序時(shí),取到的type是亂碼
解決方法:
方法一:提交前采用encodeURI兩次編碼,記住一定是兩次
1.修改以下代碼
data:{id:1, type:encodeURI(encodeURI('商品'))}2.在后臺(tái)action里要對取得的字符串進(jìn)行decode
1String type = request.getParameter("type");
2type = URLDecoder.decode(type, "UTF-8");
方法二:ajax配置contentType屬性,加上charset=UTF-8
在ajax方法中加入以下參數(shù)
1contentType: "application/x-www-form-urlencoded; charset=UTF-8"使用其它js框架或者xhr都是差不多,設(shè)置header中contentType即可,
這里關(guān)鍵是charset=UTF-8,如果沒有這個(gè),是不行的,默認(rèn)jQuery里的contentType是沒有的.
還補(bǔ)充一下jQuery里對參數(shù)已經(jīng)進(jìn)行了一次encodeURIComponent的處理
使用jQuery的ajax方法提交ajax請求,代碼如下:
1$.ajax({
2 dataType : 'json'
3 ,type : 'POST'
4 ,url : 'http://localhost/test/test.do'
5 ,data : {id: 1, type: '商品'}
6 ,success : function(data){
7
8 }
9});
問題:
提交后后臺(tái)action程序時(shí),取到的type是亂碼
解決方法:
方法一:提交前采用encodeURI兩次編碼,記住一定是兩次
1.修改以下代碼
data:{id:1, type:encodeURI(encodeURI('商品'))}2.在后臺(tái)action里要對取得的字符串進(jìn)行decode
1String type = request.getParameter("type");
2type = URLDecoder.decode(type, "UTF-8");
方法二:ajax配置contentType屬性,加上charset=UTF-8
在ajax方法中加入以下參數(shù)
1contentType: "application/x-www-form-urlencoded; charset=UTF-8"使用其它js框架或者xhr都是差不多,設(shè)置header中contentType即可,
這里關(guān)鍵是charset=UTF-8,如果沒有這個(gè),是不行的,默認(rèn)jQuery里的contentType是沒有的.
還補(bǔ)充一下jQuery里對參數(shù)已經(jīng)進(jìn)行了一次encodeURIComponent的處理