国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > AJAX > 正文

ajax中文亂碼問題解決方案

2024-09-01 08:26:39
字體:
供稿:網(wǎng)友
ajax中文亂碼問題在中文中經(jīng)常會出現(xiàn)這種問題,其實只要稍加注意就不會出現(xiàn)ajax中文亂碼這回事情了,注意前后臺編碼一致.你用的是中文.而ajax傳輸數(shù)據(jù)的時候用的是utf-8 ,還有對ajax get方法時最好escape 或urlcode,
復(fù)制代碼 代碼如下:www.mb5u.com

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

如果是用servlet就加
復(fù)制代碼 代碼如下:www.mb5u.com

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

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

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

一切都解決了
再說一下從客戶端上傳數(shù)據(jù),就必須在服務(wù)端進行編碼轉(zhuǎn)換
復(fù)制代碼 代碼如下:www.mb5u.com

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

現(xiàn)在就都是中文的了。
注意前后臺編碼一致.你用的是中文.而ajax傳輸數(shù)據(jù)的時候用的是utf-8
復(fù)制代碼 代碼如下:www.mb5u.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>

客戶端文件的編碼設(shè)置為gb2312,如下面代碼所示:
html代碼
復(fù)制代碼 代碼如下:www.mb5u.com

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

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

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

兩者原理是一樣的。
最著關(guān)鍵的是在獲取參數(shù)時應(yīng)該對獲取字符串進行重新編碼,如下面代碼所示:
復(fù)制代碼 代碼如下:www.mb5u.com

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

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

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

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

為post時應(yīng)該時這樣吧
復(fù)制代碼 代碼如下:www.mb5u.com

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 佛山市| 上思县| 当涂县| 沅陵县| 东乡族自治县| 大余县| 莎车县| 七台河市| 新兴县| 永寿县| 武川县| 万源市| 永丰县| 农安县| 鹤峰县| 泰宁县| 古田县| 清水河县| 岗巴县| 雷州市| 贵南县| 浮梁县| 高州市| 泾川县| 辽宁省| 昔阳县| 乳山市| 利辛县| 阳新县| 开封县| 安远县| 晋城| 介休市| 白朗县| 岱山县| 嘉峪关市| 荥阳市| 富阳市| 彭泽县| 方正县| 崇文区|