ajax中文亂碼問題

來源:互聯網
上載者:User

<%@ page contenttype="text/html;charset=gb2312%>
如果是用servlet就加
response.setcontenttype("text/html;charset=gb2312");
request.setcharacterencoding("gb2312");
還有一個更好的方法就是在加一個filter
在其中加入
response.setcontenttype("text/html;charset=gb2312");
request.setcharacterencoding("gb2312");
一切都解決了
 
再說一下從用戶端上傳資料,就必須在服務端進行編碼轉換
string param = request.getparamter("param");
param = new string(param.getbytes("iso-8859-1"),"gb2312");
 
現在就都是中文的了。


注意前後台編碼一致.你用的是中文.而ajax傳輸資料的時候用的是utf-8


<script>
var   oxmlhttp   =   new   activexobject( "microsoft.xmlhttp ");
oxmlhttp.open( "get ", "asp教程x.cc/content.aspx">http://dotnet.aspx.cc/content.aspx ",   false);
oxmlhttp.send()
var   ostream   =   new   activexobject( "adodb.stream ");
if(ostream   ==   null)
alert( "您的機器不支援adodb.stream. ")
else
{
ostream.type=1;
ostream.mode=3;
ostream.open()   ;
ostream.write(oxmlhttp.responsebody);
ostream.position=   0;
ostream.type=   2;
ostream.charset= "gb2312 ";
var   result=   ostream.readtext();
ostream.close();
ostream   =   null;
alert(   result);
}
</script>

用戶端檔案的編碼設定為gb2312,如下面代碼所示:

html代碼
<meta http-equiv="content-type" content="text/html; charset=gb2312" />  
  在發送的url地址中的查詢字串或者是使用post方式發送的請求內容不要使用escape函數進行編碼,切記!

  在伺服器端的jsp教程檔案也設定為gb2312編碼格式,如下面代碼所示: 

jsp 代碼
  
或者設定response的頭,如下面代碼所示:

java 代碼
response.setheader("content-type","text/html; charset=gb2312");  
兩者原理是一樣的。

  最著關鍵的是在擷取參數時應該對擷取字串進行重新編碼,如下面代碼所示:

  

java 代碼
string username = new string(request.getparameter("username").getbytes("iso8859_1"),"gb2312");   
其中,username為接收的參數。

直接使用out.print(username);就可以將中文返回給用戶端,在用戶端直接使用xmlhttp.responsetext屬性就可以直接使用返回的中文了!

  附件中我測試用的一個小例子,在tomcat6.0和resin2.1.8中通過測試!

   其實,還有一個一勞永逸的解決方案,就是添加一個過濾器。
補充一下提交方法為get時時在伺服器裡寫的時這句代碼
string username = new string(request.getparameter("username").getbytes("iso8859_1"),"gb2312");   
為post時應該時這樣吧
string username = new string(request.getparameter("username").getbytes("iso8859_1"),"utf-8"); 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.