本文介绍在JavaScript中通过URL向后台传递汉字时,因客户端GB2312与服务器UTF-8编码不一致导致的乱码问题。推荐使用encodeURIComponent进行编码,并提供了完整的ASP.NET示例代码,展示如何在前端编码及后端接收参数,有效解决特殊字符传输异常。
URL传参中文乱码问题与解决方案
借助JavaScript通过URL向后台传值是常见操作,但传递汉字时易出现字符缺失或乱码。原因在于客户端IE浏览器默认采用GB2312编码(简体中文Windows设置),而后台C#代码默认使用utf8编码。
网上解决方案如修改web.config编码为GB2312或客户端用escape预编码,体验不佳或部分特殊字符不支持。经比较,我选用encodeURIComponent在客户端编码后传值。除“/”不支持外(实际开发极少传递,若有需加判断),其他情况均适用。
encodeURIComponent的帮助文档如下:
encodeURIComponent 方法
将文本字符串编码为一个统一资源标识符 (URI) 的一个有效组件。
encodeURIComponent( encodedURIString )
必选的 encodedURIString 参数代表一个已编码的 URI 组件。
说明
encodeURIComponent 方法返回一个已编码的 URI。若将编码结果传递给 decodeURIComponent,则返回初始字符串。因该方法对所有字符编码,若字符串代表路径(如 /folder1/folder2/default.html),斜杠也会被编码,导致发送到web服务器时无效。若字符串含多个 URI 组件,请使用 encodeURI 方法编码。
要求
版本 5.5
请参阅
decodeURI 方法 | decodeURIComponent 方法
应用于: Global 对象
JavaScript前端编码实现
我做了一个小例子来展现该效果
Default.aspx代码:
代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<script type="text/javascript" language="javascript">
function callURL(Value1, Value2)
{
document.URL = "Default.aspx?Value1=" + encodeURIComponent(Value1) + "&Value2=" + encodeURIComponent(Value2);
}
</script>
<body>
<form id="form1" runat="server">
<div>
Value1=<input id="Text1" type="text" value="1234567890"/><br />
Value2=<input id="Text2" type="text" value="中华人民共和国"/>
<br />
<input id="Button1" type="button" value="提交" onclick="callURL(Text1.value, Text2.value)"/></div>
</form>
</body>
</html>C#后端参数接收代码
Default.aspx.cs代码:
代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string tmpValue1 = "";
string tmpValue2 = "";
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);
}
}