在JavaScript中通过URL传递汉字的方法
2018-09-22 01:06
  利用JavaScript通过URL方式向后台代码传值是一种经常用到的手段,但在传递汉字时经常会出现字符不全或变成乱码的问题,其原因是由于客户端IE浏览器的编码方式为GB2312(简体中文版WINDOWS的默认设置),而后台的C#代码使用utf8编码(创建WEB工程的默认配置)。 
网上有很多方案解决该问题,如将fig的编码方式改为GB2312、在客户端通过escape先编码再传,个心体会都不是很理想或有些特殊字符不支持。经过比较我决定使用encodeURIComponent在客户端进行编码,再传值,除了“/”不支持(但实际开发中很少需要传递该值,如果真有此请况,再加一层判断即可。 
encodeURIComponent的帮助文档如下: 
encodeURIComponent方法 
将文本字符串编码为一个统一资源标识符(URI)的一个有效组件。 
encodeURIComponent(encodedURIString) 
必选的encodedURIString参数代表一个已编码的URI组件。 
说明 
encodeURIComponent方法返回一个已编码的URI。如果您将编码结果传递给decodeURIComponent,那么将返回初始的字符串。因为encodeURIComponent方法对所有的字符编码,请注意,如果该字符串代表一个路径,例如/folder1/folder2/default.html,其中的斜杠也将被编码。这样一来,当该编码结果被作为请求发送到web服务器时将是无效的。如果字符串中包含不止一个URI组件,请使用encodeURI方法进行编码。 
要求 
版本5.5 
请参阅 
decodeURI方法decodeURIComponent方法 
应用于:Global对象 
我做了一个小例子来展现该效果 
Default.aspx代码: 
复制代码 代码如下:
<%@PageLanguage=C#AutoEventWireup=trueCodeFile=Default.aspx.csInherits=_Default%> 
<!DOCTYPEhtmlPUBLIC-//W3C//DTDXHTML1.0Transitional//EN
<htmlxmlns=
<headrunat=server> 
<title>无标题页</title> 
</head> 
<scripttype=text/javascriptlanguage=javascript> 
functioncallURL(Value1,Value2) 
{ 
document.URL=Default.aspx?Value1=+encodeURIComponent(Value1)+&Value2=+encodeURIComponent(Value2); 
} 
</script> 
<body> 
<formid=form1runat=server> 
<div> 
Value1=<inputid=Text1type=textvalue=1234567890/><br/> 
Value2=<inputid=Text2type=textvalue=中华人民共和国/> 
<br/> 
<inputid=Button1type=buttonvalue=提交onclick=callURL(Text1.value,Text2.value)/></div> 
</form> 
</body> 
</html> 
Default.aspx.cs代码: 
复制代码 代码如下:
usingSystem; 
usingSystem.Data; 
usingSystem.Web; 
usingSystem.Web.Security; 
usingSystem.Web.UI; 
usingSystem.Web.UI.WebControls; 
usingSystem.Web.UI.WebControls.WebParts; 
usingSystem.Web.UI.HtmlControls; 
publicpartialclass_Default:System.Web.UI.Page 
{ 
protectedvoidPage_Load(objectsender,EventArgse) 
{ 
stringtmpValue1=; 
stringtmpValue2=; 
if(Request.QueryString[Value1]!=null) 
{ 
tmpValue1=Request.QueryString[Value1].ToString(); 
} 
if(Request.QueryString[Value2]!=null) 
{ 
tmpValue2=Request.QueryString[Value2].ToString(); 
} 
Response.Write(Value1=+tmpValue1+<br/>+Value2=+tmpValue2); 
} 
}
上一篇:json 定义
文章标题:在JavaScript中通过URL传递汉字的方法
文章链接:http://soscw.com/index.php/essay/17098.html