Jquery ajax done callback not responding to 201

馋奶兔 提交于 2019-12-08 16:37:36

问题


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");
    }
  }
});


来源:https://stackoverflow.com/questions/14988666/jquery-ajax-done-callback-not-responding-to-201

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!