您好,欢迎访问一九零五行业门户网

在JavaScript中通过URL传递汉字的方法_javascript技巧

利用javascript通过url方式向后台代码传值是一种经常用到的手段,但在传递汉字时经常会出现字符不全或变成乱码的问题,其原因是由于客户端ie浏览器的编码方式为gb2312(简体中文版windows的默认设置),而后台的c#代码使用utf8编码(创建web工程的默认配置)。
网上有很多方案解决该问题,如将web.config的编码方式改为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代码:
复制代码 代码如下:
nbsp;html public -//w3c//dtd xhtml 1.0 transitional//en http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd>
无标题页
value1=
value2=
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 + 
 + value2=  + tmpvalue2); 
    } 
}
其它类似信息

推荐信息