JS传参出现乱码的种种分析


通常情况下,在web页面中引用js脚本输出内容是会出现乱码,这是由于js的编码和.net的编码方式不同造成的。
通常js的编码格式是Utf-8,.NET的编码格式是gb2312。如果两者编码方式不一致,那么乱码就出现了。
解决方法:
一种方法是在配置文件中的<system.web></system.web>节点内部添加
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312" />节点,
另一种方法是在页面使用:
<meta http-equiv="content-type" content="text/html;charset=gb2312">
第三种方法是传递中文之前,将要传递的中文参数进行编码,在接收时再进行解码。
传参:
string Name = "中文参数";
Response.Redirect("B.aspx?Name="+Server.UrlEncode(Name)) ;
解码:
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name)) ;
如果是从html文件向aspx或ashx文件进行传递中文参数的话,一样要将传递的中文参数进行编码,在接收时再进行解码。
例如:
<script language="JavaScript">
function GoUrl()
{
var Name = "中文参数";
location.href = "B.aspx?Name="+escape(Name) ;
}
<body onclick="GoUrl()">
接收:
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name)) ;

js传递参数到ashx中处理:

url: 'http://www.cnblogs.com/ajax/ajax_User.ashx?Action=Search&conditions=' + escape(info),

string info = context.Server.HtmlDecode(context.Request.QueryString["conditions"]).ToString();


总结:
一般来说。设置web.config文件就可以了。但是如果你用 JavaScript 调用 webservice 方法的话(往webservice里面传递中文参数)。
设置 web.config 文件好象无效。或用
Response.Redirect("test1.aspx?111="+System.Web.HttpUtility.UrlEncode("中文")) ;
建议使用最后如果是从其他的页面获取中文参数没有乱码,那就更简单了
string message ="http://www.cnblogs.com/A.aspx?111="+System.Web.HttpUtility.UrlEncode("中文");
//发送请求
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(message) ;
//接受请求
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse() ;
Stream receiveStream = myHttpWebResponse.GetResponseStream() ;
StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.GetEncoding("GB2312")) ;
//此为要取页面的返回值输出的返回结果
returnValue = readStream.ReadToEnd();
 

原文地址:https://www.cnblogs.com/jsping/p/2809879.html