-->

Jquery ajax done callback not responding to 201

2019-06-15 10:46发布

问题:

I have an ajax post as such:

$.post("/api/v1/payment_methods/create_credit_card", values)
.done (response) ->
  console.log("GOOD JOB")
.fail (response) ->
  console.log("Adas")

The response is a 201, however, done doesn't seem to be capturing it and instead it's going to fail. I thought 201 would of been considered a success and would of been captured by done. Any ideas of why it wouldn't be working?

Note: The above code is in coffeescript, which doesn't really affect the question but explains my syntax

回答1:

So we figured out what was wrong, JSON.parse was throwing a Syntax Error - so the values sent in isnt in a valid JSON format. The poster wasnt able to see the Syntax error in chrome, but firebug showed the error.

This indicates that whenever Javascript will throw an exception, the response might still be 200, 201, 202 etc. - but because of the syntax error the fail() function would be triggered.

EDIT - Also you should probably use a different response, many use 200 - OK, but Id recommend to use 202 - ACCEPTED in this case.



回答2:

Looking at the source, success should fire for anything between 200 - 300 and 304. An alternative is to explicitly call out the statusCode:

$.ajax({
  statusCode: {
    201: function() {
      console.log("HERE");
    }
  }
});