一句话解决AJAX中文乱码问题[推荐]
一句话解决AJAX中文乱码问题[推荐]
发布时间:2016-12-29 来源:查字典编辑
摘要:下面是我的程序HTML:复制代码代码如下:无标题页varxmlhttp;functioncreateXMLHttprequest(){if(...

下面是我的程序

HTML :

复制代码 代码如下:

<!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>

<title>无标题页</title>

<script type="text/javascript" language="javascript">

var xmlhttp;

function createXMLHttprequest()

{

if(window.ActiveXObject)

{

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

else if(window.XMLHttpRequest)

{

xmlhttp=new XMLHttpRequest();

}

}

function inData()

{

var txtval=document.getElementById("txt").value;

createXMLHttprequest();

xmlhttp.open("GET","request.ashx?val="+txtval,true);

xmlhttp.onreadystatechange=getData;

xmlhttp.send(null);

}

function getData()

{

if(xmlhttp.readyState==4)

{

if(xmlhttp.status==200)

{

document.getElementById("showDT").innerHTML=xmlhttp.responseText;

}

}

}

</script>

</head>

<body>

<form id="form1" action="">

<div>请输入姓名:

<input type="text" id="txt" />

<input type="button" value="提交" id="asdf" />

<span id="showDT" ></span>

</div>

</form>

</body>

</html>

request.ashx :

Code

复制代码 代码如下:

<%@ WebHandler Language="C#" %>

using System;

using System.Web;

public class request : IHttpHandler {

public void ProcessRequest (HttpContext context) {

context.Response.ContentType = "text/plain";

string tab ="来自服务器的信息:您好 "+context.Request.QueryString["val"].ToString()+" --by time:"+DateTime.Now.ToLongTimeString();

context.Response.Write(tab);

}

public bool IsReusable {

get {

return false;

}

}

}

baidu搜了一大堆 大致意思是 AJAX提交数据时,使用的是UTF-8的编码 并且不可以设置为其他格式

如何解决呢 最后发现一个JS的函数escape与unescape 用escape()对将要提交的汉字进行编码,会出现大致%10%20的字符,类似与.NET中Server.UrlEncode()与Server.UrlDecode();

将JS获得的表单值进行重新编码

Code

复制代码 代码如下:

var txtval=escape(document.getElementById("txt").value);

OK, 问题解决!

其他可能还有别的办法至今没遇到 希望这个办法能帮到遇到这种困境的朋友

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新AJAX相关学习
热门AJAX相关学习
编程开发子分类