JS代码:
function SearchIndex()
{
var name =
$("#inputName").val();
var urls =
"../../ServAction/index/nameSearch.ashx?action=single&Name=" +
name ;
$.ajax({
type: 'POST',
contentType:
"application/x-www-form-urlencoded:charset=UTF-8",
url: urls,
dataType: 'json',
success: function (datat) {
showData(datat);
}
});
}
在ashx处理程序中:
public void ProcessRequest(HttpContext context)
{
string straction = context.Request["action"];
string strResult = string.Empty;
string stringName = context.Request["Name"];
strResult
= new ClsDataBaseOperation().getResult(stringName);
context.Response.Write(strResult);
}
注意:
contentType:
"application/x-www-form-urlencoded:charset=UTF-8",
加了这句,在谷歌浏览器测试没问题的,但在IE浏览器中,stringName就出现了中文乱码。
而在ProcessRequest函数添加了以下一句:
context.Request.ContentEncoding =
Encoding.GetEncoding("gb2312");
此时IE的中文传值正常,即stringName没有乱码。但谷歌浏览器中却乱码了。
经过测试,最终解决方案如下:
JS代码:
function SearchIndex()
{
var name =
encodeURI($("#inputName").val());//对该中文参数进行编码var urls
= "../../ServAction/index/nameSearch.ashx?action=single&Name="
+ name ;
$.ajax({
type: 'POST',
contentType:
"application/x-www-form-urlencoded:charset=UTF-8",
url: urls,
dataType: 'json',
success: function (datat) {
showData(datat);
}
});
}
在ashx处理程序中:
//context.Request.ContentEncoding =
Encoding.GetEncoding("gb2312");//注释这一句
string stringIndexName =context.Server.HtmlDecode(
context.Request["indexName"]);//对传过来的参数进行解码。测试过程发现,这句不用改也可以,即不用这句,也能自动解码