[转]AJAX中关于responseText乱码问题

默认分类 | 2006-06-22 22:10:00 | 阅读 3013 次 | 评论(1)
用AJAX来GET回一个页面时,RESPONSETEXT里面的中文多半会出现乱码,这是因为xmlhttp在处理返回的responseText的时候,是把resposeBody按UTF-8编码进解码考形成的,如果服务器送出的确实是UTF-8的数据流的时候汉字会正确显示,而送出了GBK编码流的时候就乱了。解决的办法就是在送出的流里面加一个HEADER,指明送出的是什么编码流,这样XMLHTTP就不会乱搞了。

PHP:header('Content-Type:text/html;charset=GB2312');
ASP:Response.Charset("GB2312")
JSP:response.setHeader("Charset","GB2312");

checkname1.html
---------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>帐号检测</title>
</head>
<body>
  <script type="text/javascript" language="javascript">
    var http_request = false;
    function makeRequest(url) {
        http_request = false;
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = alertContents;
   http_request.open('POST', url, true);
        http_request.send(null);
    }
    function alertContents() {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
   
      document.getElementById('aa').innerHTML=http_request.responseText;
     
      //hello=http_request.responseText;
     //document.getElementById('aa').innerHTML=http_request.responseText;
            } else {
              alert('There was a problem with the request.');
            }
        }
    }
 
 function userCheck() {
 var f = document.form1;
 var us
文章评论,共1条
icecool
2006-08-10 01:33
1
呵呵,不客气,也最近搞搞这个的.
游客请输入验证码