【问题标题】:IE ajax sending utf8 chars as?IE ajax 发送 utf8 字符为?
【发布时间】:2012-06-01 16:24:31
【问题描述】:

考虑$("#"+id).val()

var field = document.getElementById( id );
/* ... */
if( field.value != "" )
    var jqxhr = $.get( "/user/ajaxtag/tag/" + $("#"+id).val(), function( data ) {
        suggestionText = data;
        //does something which i thing is non of problem's business
        var arr = getListItems( field.value );
        if ( field.value.length > 0 ){
            createList( arr );
        } else {
            clearList();
        };
        // end of non of business
    });

当在输入框中使用英文触发这段代码变化时,ajax请求响应成功,但是当使用像“س”这样的波斯语时,IE发送了这个

GET /user/ajaxtag/tag/??_=1338567574102 HTTP/1.1\r\n

(我在 wireshark 上得到了这个信息)并将 utf8 字符替换为?,当我使用 firefox 时不会出现问题,仅在 ie 中(并不奇怪哈?)我在标题中有这一行

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

在 stackoverflow.com 上的另一个问题中,有人建议更改 php.ini,但我在共享主机上并且无权访问该文件。

我做了alert( $( "#" + id ).val() ) 并且警告的事情不是?是输入字符.. 就像 س

【问题讨论】:

    标签: javascript jquery internet-explorer utf-8


    【解决方案1】:

    您需要使用 encodeURIComponent() 函数对参数名称和值进行编码。

    或使其符合 RFC3986,您可以使用此功能:

    /** 
     * encodeURIComponent() function is not 100% compatible with
     * RFC3986 http://www.faqs.org/rfcs/rfc3986.html
     */
    function encodeRFC3986(value) {
      return encodeURIComponent(value)
        .replace(/!/g,  "%21")
        .replace(/\*/g, "%2A")
        .replace(/\(/g, "%28")
        .replace(/\)/g, "%29")
        .replace(/'/g,  "%27");
    }
    

    【讨论】:

    • 是的,它应该像var jqxhr = $.get("/user/ajaxtag/tag/"+encodeURIComponent($("#"+id).val()), function(data) {...一样被替换,谢谢...
    • 为什么遵守 RFC3986 很重要?
    • 一些平台要求字符串以 RFC3986 格式编码,encodeURIComponent() 不是 100% 兼容,我发布这个是为了回答完整性
    • 当某些东西在 IE 和其他主要浏览器(通常是 chrome 和 firefox)中运行时,它总是让我感到安全,没有勇气让我的代码变得更好,顺便说一句,记住标准很重要。谢谢你..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2021-11-18
    • 1970-01-01
    • 2016-02-17
    相关资源
    最近更新 更多