今天上午做項目時候因為要用到ajax異步提交數(shù)據(jù),這里我用的是prototype.js里包的ajax對象,大家也可以自己實現(xiàn)XMLHttpRequest對象,vm頁面用的是gbk編碼(如果是utf-8就不會有問題了),這個url帶有兩個參數(shù),一個是id,一個是漢字內(nèi)容,浪費了不少時間!以下是說明:
例如如下js:
function editPollDetail(pollDetailId,pollId)
{
var xuanxiangneirong=document.getElementById('xuanxiangneirong'+pollDetailId);
var url = 'createThread.do';
var pars = 'method=editOnePollDetail&pollDetailId='+pollDetailId+'&content='+xuanxiangneirong.value+'&pollId='+pollId;
var ajax = new Ajax.Request(url,{method:'post',parameters:pars,onComplete:showEditResult});
}
其中xuanxiangneirong是中文,開始我用了很多方法,在action中utf-8,gbk ,iso8859-1相互轉(zhuǎn)換,用了3的排列的可能全試了, 就是不行。于是上網(wǎng)又轉(zhuǎn)了很長時間看了很多,還是不行,最后我自己解決了這個問題,代碼如下:
function editPollDetail(pollDetailId,pollId)
{
var xuanxiangneirong=document.getElementById('xuanxiangneirong'+pollDetailId);
var url = 'createThread.do';
var pars = 'method=editOnePollDetail&pollDetailId='+pollDetailId+'&content='+encodeURI(encodeURI(xuanxiangneirong.value))+'&pollId='+pollId; //注意這里用了兩次js的encodeURI進(jìn)行轉(zhuǎn)碼。
var ajax = new Ajax.Request(url,{method:'post',parameters:pars,onComplete:showEditResult});
}
在action中做如下的處理:
public ActionForward editOnePollDetail(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/plain; charset=GBK");
String id=request.getParameter("pollDetailId");
String pollid=request.getParameter("pollId");
String content=request.getParameter("content");
try
{
content=URLDecoder.decode(content,"utf8"); //因為ajax默認(rèn)是utf-8編碼,這里將剛才的轉(zhuǎn)碼進(jìn)行解析,這樣得到就是你要傳的漢字了。
System.out.println(content);
}catch(Exception e)
{
System.out.println("解碼出現(xiàn)異常");
e.printStackTrace();
}
}
大家可以做個demo,不過建議大家以后頁面都用utf-8的,這樣就能避免這些問題。