What changed in jQuery 1.9 to cause a $.ajax call to fail with syntax error

后端 未结 3 962
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-06 23:12

I\'m making a REST DELETE call, which returns a 204. In jQuery 1.8.3 this works, and hits the request.done callback. But if I use 1.9 it goes to request.fail with a parsererror

3条回答
  •  抹茶落季
    2021-02-06 23:45

    The problem seems to be that jQuery treats the empty body (where Content-Length is 0) of a 204 response as "". Which is one interpretation, but the downside is that "" gets treated like any other response string. So if you have called jQuery.ajax() with the dataType:json option, jQuery tries to convert "" to an object and throws an exception ("" is invalid JSON).

    jQuery catches the exception and recovers, but if you prefer to avoid the exception altogether (in your development environment) you might do something like the following. Add in the "converters" option to jQuery.ajax() and use it to change "" responses to nulls (I do this when dataType is json). Something like :

    var ajax_options =
        {
            /* ... other options here */
            "converters" :
                {
                    "text json" :
                        function( result )
                        {
                            if ( result === "" ) result = null;
                            return jQuery.parseJSON( result );
                        }
                }
        };
    
    var dfd = jQuery.ajax( ajax_options );
    

提交回复
热议问题