简体   繁体   中英

jQuery ajax not transmitting as utf-8

I'm using an older version of backbone.js (0.5.3) with jQuery 1.7.2, and when Backbone.sync executes (which is a wrapper for jQuery $.ajax()) it sets the contentType explicitly as:

params.contentType = 'application/json';

This looks like what I want, however the content doesn't appear to be sent as utf-8. I'm testing with an ndash, here is my sample string:

Mathematics K–10

After submitting to the server I get:

Mathematics K–10

Now, if I change the contentType (in backbone.js) to:

params.contentType = 'application/json; charset=utf-8';

Everything works as expected and I get the correct ndash character. This is also the behaviour if I comment out the original contentType line in backbone.

The jQuery docs suggest that:

Data will always be transmitted to the server using UTF-8 charset

But it seems that if you explicitly set your contentType, then you also need to set a character set.

My question is, does this behaviour make sense? I would have thought we always want the default to be utf-8 (as the jQuery docs state) even if we explicitly change the contentType. Has anyone else come across this or have any information that might help me out?

You could extend the ajax function to provide custom headers for backbone ajax calls, like the above,

Backbone.ajax = (function(_protoAjax) {
    var _Backboneajax = _protoAjax;
    return function(options) {
        var defaultOptions = {
            headers: {
                "Accept": "application/json; charset=UTF-8",
                "Content-Type": "application/json; charset=UTF-8"
            }
        };
        options = $.extend({}, defaultOptions, options)
        return _Backboneajax.call(this, options);
    };
})(Backbone.ajax);  

Or you could set this headers on all JQuery Ajax calls (not only the Backbone ajax calls), like the above,

$.ajaxSetup({
    headers: {
        "Accept": "application/json; charset=UTF-8",
        "Content-Type": "application/json; charset=UTF-8"
    }
});

The HTTP spec states the the content-type sets the character sense. Perhaps the jQuery docs should be clearer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM