ajax中文亂碼問題解決方案_AJAX教程

      編輯Tag賺U幣

      推薦:AJAX避免用戶重復提交請求實現方案
      為了避免因某些原因用戶同時多次點擊按鈕,提交重復的請求,我們需要禁用請求提交按鈕,接下來與大家一起分享下實現方法

      ajax中文亂碼問題在中文中經常會出現這種問題,其實只要稍加注意就不會出現ajax中文亂碼這回事情了,注意前后臺編碼一致.你用的是中文.而ajax傳輸數據的時候用的是utf-8 ,還有對ajax get方法時最好escape 或urlcode,
      復制代碼 代碼如下:www.wf0088.com

      <%@ page contenttype="text/html;charset=gb2312%>

      如果是用servlet就加
      復制代碼 代碼如下:www.wf0088.com

      response.setcontenttype("text/html;charset=gb2312");
      request.setcharacterencoding("gb2312");

      還有一個更好的方法就是在加一個filter
      在其中加入
      復制代碼 代碼如下:www.wf0088.com

      response.setcontenttype("text/html;charset=gb2312");
      request.setcharacterencoding("gb2312");

      一切都解決了
      再說一下從客戶端上傳數據,就必須在服務端進行編碼轉換
      復制代碼 代碼如下:www.wf0088.com

      string param = request.getparamter("param");
      param = new string(param.getbytes("iso-8859-1"),"gb2312");

      現在就都是中文的了。
      注意前后臺編碼一致.你用的是中文.而ajax傳輸數據的時候用的是utf-8
      復制代碼 代碼如下:www.wf0088.com

      <script>
      var oxmlhttp = new activexobject( "microsoft.xmlhttp ");
      oxmlhttp.open( "get ", "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代碼
      復制代碼 代碼如下:www.wf0088.com

      <meta http-equiv="content-type" content="text/html; charset=gb2312" />

      在發送的url地址中的查詢字符串或者是使用post方式發送的請求內容不要使用escape函數進行編碼,切記!
      在服務器端的jsp教程文件也設置為gb2312編碼格式,如下面代碼所示:
      jsp 代碼
      或者設置response的頭,如下面代碼所示:
      復制代碼 代碼如下:www.wf0088.com

      response.setheader("content-type","text/html; charset=gb2312");

      兩者原理是一樣的。
      最著關鍵的是在獲取參數時應該對獲取字符串進行重新編碼,如下面代碼所示:
      復制代碼 代碼如下:www.wf0088.com

      string username = new string(request.getparameter("username").getbytes("iso8859_1"),"gb2312");

      其中,username為接收的參數。
      直接使用out.print(username);就可以將中文返回給客戶端,在客戶端直接使用xmlhttp.responsetext屬性就可以直接使用返回的中文了!
      附件中我測試用的一個小例子,在tomcat6.0和resin2.1.8中通過測試!

      其實,還有一個一勞永逸的解決方案,就是添加一個過濾器。
      補充一下提交方法為get時時在服務器里寫的時這句代碼
      復制代碼 代碼如下:www.wf0088.com

      string username = new string(request.getparameter("username").getbytes("iso8859_1"),"gb2312");

      為post時應該時這樣吧
      復制代碼 代碼如下:www.wf0088.com

      string username = new string(request.getparameter("username").getbytes("iso8859_1"),"utf-8");

      分享:ajax的 IE cache 相關問題解決
      運用Ajax做了一個名字檢驗,第一次是有效的,但是提交過后,再檢驗一次,結果就不對了,是由于IE的cache的原因,接下來介紹下詳細的解決方法,感性的朋友可以參考下哈

      來源:模板無憂//所屬分類:AJAX教程/更新時間:2013-04-22
      相關AJAX教程