qygh 发表于 2011-4-1 04:48:38

ajax中文乱码问题

初学Ajax,在做实例时,发现了一个问题,就是使用Ajax获取中文时,会产生乱码,在此请教各位。

实例代码如下所示:

<html>
<head>
<title> Ajax实例 </title>
<script   language= "javascript "   type= "text/javascript ">
<!--
var   xmlHttp;
function   createXMLHttpRequest()
{
if   (window.ActiveXObject)
{
xmlHttp   =   new   ActiveXObject( "Microsoft.XMLHTTP ");
}
else   if   (window.XMLHttpRequest)
{
xmlHttp   =   new   XMLHttpRequest();
}
}

function   httpStateChange()
{
if   (xmlHttp.readyState==4)
{
if   (xmlHttp.status==200   ||   xmlHttp.status==0)
{
var   node   =   document.getElementById( "myDiv ");
node.firstChild.nodeValue   =   xmlHttp.responseText;
}
}
}

function   getData()
{
createXMLHttpRequest();
if   (xmlHttp!=null)
{
xmlHttp.open( "get ", "ajax.txt ",true);
xmlHttp.onreadystatechange   =   httpStateChange;
xmlHttp.send(null);
}
}
-->
</script>
</head>
<body>
<div   id= "myDiv "> 原数据 </div>
<input   type= "button "   value= "更新数据 "  >
</body>
</html>

获取的ajax.txt文件与hmtl文件放在同一个文件夹下。
如果将ajax.txt在记事本中存为ansi编码,则使用IE6、opera9、netscape7和firefox2打开为乱码。
如果将ajax.txt在记事本中存为unicode编码和Unicode   big   endian编码,则使用IE6、opera9都能正常打开,但是使用netscape7和firefox2,打开为乱码。
如果将ajax.txt在记事本中存为utf-8编码,则使用IE6、opera9和firefox2都能正常打开,但是使用netscape7打开为乱码。

最后总结是,无论将ajax.txt文件存为什么编码,Netscape7都不能将中文正确显示出来。请问,该问题要如何解决?
=====================================================================================
如果将ajax.txt在记事本中存为utf-8编码,则使用IE6、opera9和firefox2都能正常打开,但是使用netscape7打开为乱码。

那就放弃netscape7吧O.o
=====================================================================================
function   getData()
{
createXMLHttpRequest();
if   (xmlHttp!=null)
{
xmlHttp.open( "get ", "ajax.txt ",true);
xmlHttp.onreadystatechange   =   httpStateChange;
xmlHttp.send(null);
}
}


改成:
function   getData()
{
createXMLHttpRequest();
if   (xmlHttp!=null)
{
xmlHttp.open( "get ", "ajax.txt ",true);
xmlHttp.setRequestHeader( 'Content-type ', 'application/x-www-form-urlencoded ');
xmlHttp.onreadystatechange   =   httpStateChange;
xmlHttp.send(null);
}
}
试试
========================================================================================
页: [1]
查看完整版本: ajax中文乱码问题