告诉你怎样解决Ajax中文乱码问题

  • 来源:网络
  • 更新日期:2020-08-03

摘要: js代码: 得到XmlHttpRequest的类 Code function HttpRequest() { //取得Request对象 this.Request=function(){ try {

js代码:

得到XmlHttpRequest的类

Code

function HttpRequest()
{
//取得Request对象
this.Request=function(){
try
{
if(window.XMLHttpRequest) request=new XMLHttpRequest();
if(!request)request=new ActiveXObject(Microsoft.XMLHTTP);
if(!request)request=new ActiveXObject(Msxml2.XMLHTTP);
return request;
}
catch(e)
{
alert(不支持XMLHTTPRequest);
}}
}

调用过程:

Code

<%@ Page Language=C# AutoEventWireup=true CodeBehind=Default.aspx.cs Inherits=AjaxTest._Default  %>

<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<html xmlns=http://www.w3.org/1999/xhtml>
<head runat=server>
<title>Untitled Page</title>
<script language=javascript type=text/javascript src=User.Base.js></script>
<script language=javascript type=text/javascript>
function Check()
{
var request=new HttpRequest().Request();
request.onreadystatechange=function (){
if(request.readyState==4)
{
if(request.status==200)
{
alert(request.responseText);
}
else
{
alert(request.responseText);
}
}
}
var value=document.getElementById(val).value;
request.open(POST,Default.aspx?Value=+value,true);
//设置防止乱码的方法,只要一句话就行
request.setRequestHeader(Content-Type,text/html;charset=gb2312);
request.send(null);
}
</script>

</head>
<body>
<form id=form1 runat=server>
<div>
<input id=val type=text onblur=Check() />
</div>
</form>
</body>
</html>


后台取得输入值:

protected void Page_Load(object sender, EventArgs e)
{
string value = Request[Value];
}

测试过,可以得到正确的输入字符。