用户登录
用户注册

分享至

一句话解决AJAX中文乱码问题[推荐]

  • 作者: 段子青年
  • 来源: 51数据库
  • 2021-09-21
下面是我的程序
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.51sjk.com/Upload/Articles/1/0/270/270344_20210708034332257.jpg">
<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" onclick="indata()" />
<span id="showdt" ></span>
</div>
</form>
</body>
</html>

request.ashx :
code 
复制代码 代码如下:

<%@ webhandler language="c#" class="request" %>
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, 问题解决!
其他可能还有别的办法至今没遇到 希望这个办法能帮到遇到这种困境的朋友
软件
前端设计
程序设计
Java相关