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

后端 未结 3 963
爱一瞬间的悲伤
爱一瞬间的悲伤 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:54

    An HTTP 204 response is not an empty string: it means there is no data. This is a valid response for delete and update operations.

    This looks like a bug introduced in JQuery 1.9.

    The reason removing the dataType property fixes this is because when it's set to "json" JQuery attempts to parse the content using JSON.parse and failing as a result. From the ticket:

    This won't fail with any other dataType than "json" because the regression is due to the re-alignment of parseJSON with native JSON.parse (throwing an exception for null/undefined values).

    Don't try the workaround suggested in the ticket of adding a handler for the 204 via the statusCode property, because both that handler and the error handler will be triggered. A possible solution is the following:

        $.ajax(url, {
        type: "DELETE",
        dataType: "json",
        error: function (error) {
            if (error.status === 204) {
                // Success stuff
            }
            else {
                // fail
            }
        }});
    

提交回复
热议问题