jquery向.ashx文件post中文乱码问题的解决方法

1.我的环境:vs2005,未装SP1补丁,不能创建Web应用程序,只能创建网站;jquery版本1.5.1

2.web.config中的相关配置

<globalization requestEncoding="gb2312" responseEncoding="gb2312"/>

3.jquery的Post数据的写法

复制代码 代码如下:


$(document).ready(function (){
$("#btnSend").click(function(){
$.ajax({
type: "POST",
url: "PrecisionAHandle.ashx",
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
data: { "StudentId": $("#LblStudentId").attr("innerText"),"StudentName": $("#LblStudentName").attr("innerText"),"StudentAge": $("#txtStudentAge").attr("value")},
success: function(html){
$("#TabContainer").html(html);
}
});
});
});


其中StudentName是中文

4.在.ashx文件中接收参数的写法

string strStudentName = context.Request.Params["StudentName"];
注意:如果没有contentType:"application/x-www-form-urlencoded; charset=UTF-8",则context.Request.Params["StudentName"]是乱码。
经过在.ashx中跟踪context.Request.ContentEncoding,可知jquery所post过来的数据采用的是gb2312编码,可能context.Request在接收到数据时默认采用utf-8进行解码,但是jquery在Post数据的时候却不是用的utf-8才导致.ashx的context.Request.Params["StudentName"]显示为乱码。
感觉比较奇怪的现象:
现象1:在不添加contentType:"application/x-www-form-urlencoded; charset=UTF-8",的情况下,在.ashx文件中使用下面的语句却可以正确显示字符串:

复制代码 代码如下:


StreamReader steamRd = new StreamReader(HttpContext.Current.Request.InputStream);
string strPostData = steamRd .ReadToEnd();
strPostData =HttpUtility.UrlDecode(strPostData, Encoding.GetEncoding("utf-8"));


现象2:将web.config中的相关配置改为
<globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
之后,不管是否加上contentType:"application/x-www-form-urlencoded; charset=UTF-8",后台的.ashx文件接收到的参数仍然是乱码。修改web.config之后网站编译的很慢且运行的也很慢。

参考文章:
https://www.jb51.net/article/26658.htm
https://www.jb51.net/article/26659.htm

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdfdys.html