开发者

JQuery AJAX Call with Unicode. Proper way to POST Unicode data?

I have page that POSTS AJAX to the server, and often 开发者_JS百科the data will be Unicode.

This works most the time, but it appears that sometimes it's breaking and I'm can't seem to find the answer anywhere. I have been using encodeURI, but I'm not sure that's correct.

Here's a example of the code:

    $.ajax({
       type: "POST",
       url: "SomePage.php",
       data: "val1=" + encodeURI(unicodeVariable) + "&presentation=" + encodeURI(someUnicodeVariable),
       success: function(msg){

       }
     });                    

I'm guessing what's happening is sometimes a Unicode character includes an & that's breaking it.

What's the correct way to encode Unicode for an AJAX call with JQuery?

Thanks.


Here's a good link that compares all of the encoding methods.

Lastly, the encodeURIComponent() method should be used in most cases when encoding a single component of a URI. This method will encode certain chars that would normally be recognized as special chars for URIs so that many components may be included. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURIComponent() encodes also the "&" symbol:

encodeURI("&"); // "&"
encodeURIComponent("&"); // "%26"

Or you can just convert this line:

data: "val1=" + encodeURI(unicodeVariable) + "&presentation=" + encodeURI(someUnicodeVariable),

into an object:

data: {
    val1: unicodeVariable,
    presentation: someUnicodeVariable
}

And jQuery will automatically make sure the data is encoded, using encodeURIComponent().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜