现在的位置: 首页 > 综合 > 正文

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

2012年07月17日 ⁄ 综合 ⁄ 共 1748字 ⁄ 字号 评论关闭

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

2.web.config中的相关配置

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

3.jquery的Post数据的写法

jquery Code

$(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文件中使用下面的语句却可以正确显示字符串:

View Code

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之后网站编译的很慢且运行的也很慢。

参考文章:

1)http://dev.firnow.com/course/1_web/javascript/jsjs/20090303/157078.html
2)http://xyztony1985.blog.163.com/blog/static/361178201081754921150/

抱歉!评论已关闭.