Ajax以post方式汉字乱码解决

文件为gb2312编码

test.php

<SCRIPT LANGUAGE="javascript">
<!--      
function saveUserInfo()
{
    //获取接受返回信息层
    var msg = document.getElementById("msg");
    //获取表单对象和用户信息值
    var f = document.user_info;    
    var username = f.username.value;
    //接收表单的URL地址
    var url = "commit.php";    
    //需要POST的值,把每个变量都通过&来联接
    var postStr = "username="+ UrlEncode(username);
    //实例化Ajax
    var ajax = null;
    if(window.XMLHttpRequest){
        ajax = new XMLHttpRequest();
       }
    else if(window.ActiveXObject){
        ajax = new ActiveXObject("Microsoft.XMLHTTP");
       }
    else{
        return;
       }

    //通过Post方式打开连接
    ajax.open("POST", url, true);
    //定义传输的文件HTTP头信息
    ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //发送POST数据
    ajax.send(postStr);

    //返回数据的处理函数
    ajax.onreadystatechange = function(){
        if (ajax.readyState == 4 && ajax.status == 200){
    alert(ajax.responseText);
               msg.innerHTML = ajax.responseText;
            }
      }
}
-->
</SCRIPT>
<script language="vbscript">
Function str2asc(strstr)
 str2asc = hex(asc(strstr))
End Function
Function asc2str(ascasc)
 asc2str = chr(ascasc)
End Function
</script>
<script language="javascript">
/*这里开始时UrlEncode和UrlDecode函数*/
function UrlEncode(str){
  var ret="";
  var strSpecial="!"#$%&'()*+,/:;<=>?[]^`{|}~%";
  var tt= "";

  for(var i=0;i<str.length;i++){
   var chr = str.charAt(i);
    var c=str2asc(chr);
    tt += chr+":"+c+"n";
    if(parseInt("0x"+c) > 0x7f){
      ret+="%"+c.slice(0,2)+"%"+c.slice(-2);
    }else{
      if(chr==" ")
        ret+="+";
      else if(strSpecial.indexOf(chr)!=-1)
        ret+="%"+c.toString(16);
      else
        ret+=chr;
    }
  }
  return ret;
}
function UrlDecode(str){
  var ret="";
  for(var i=0;i<str.length;i++){
   var chr = str.charAt(i);
    if(chr == "+"){
      ret+=" ";
    }else if(chr=="%"){
     var asc = str.substring(i+1,i+3);
     if(parseInt("0x"+asc)>0x7f){
      ret+=asc2str(parseInt("0x"+asc+str.substring(i+4,i+6)));
      i+=5;
     }else{
      ret+=asc2str(parseInt("0x"+asc));
      i+=2;
     }
    }else{
      ret+= chr;
    }
  }
  return ret;
}
</script>
<form name="user_info">
姓名:<input type="text" name="username" /><br/>
<input type="button" value="提交表单" onClick="saveUserInfo()">
</form>
<div id="msg"></div>

commit.php

<?php
 header("content-type:text/html;charset=gb2312");
 echo "哈罗";
 echo $_POST["username"];
?>

    A+
发布日期:2009年08月19日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: