jquery ajax在失败时不解析json [英] jquery ajax does not parse json on failure

查看:81
本文介绍了jquery ajax在失败时不解析json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery的jqXHR对象在失败时传递给回调并不解析json响应,因此responseJSON未定义只有responseText可用。

jQuery's jqXHR object passed to the callback on failure does not parse json responses, therefore responseJSON is undefined only responseText is available.

它适用于成功的请求,I我使用设置正确的标题数据类型:'json'

It works fine for successful requests, I am setting the correct headers using dataType: 'json'

致电:

  $.ajax({
    type: 'POST',
    url: $form.attr('action'),
    data: post_data,
    dataType: 'json',
    done: done_callback,
    fail: fail_callback,
    always: always_callback
  });

请求标题:

Accept:application/json, text/javascript, */*; q=0.01
X-Requested-With:XMLHttpRequest
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.83 Safari/535.11

响应标题:

Content-Type:application/json;charset=utf-8
Status:500

responseText:

responseText:

{"status":"error","code":500,"message":"A system error occurred, please try again later"}

responseJSON未定义

responseJSON is undefined

当ajax请求的响应失败时,jQuery是否解析json?
我找不到任何要确认的文档或否认这种行为(我可能只是看起来不够努力)

我显然可以使用 parseJSON 失败回调中。

I can obviously just use parseJSON in the fail callback.

推荐答案

我看了一下jQuery ajax回调方法OD。仅当(状态> = 200&& status< 300 || status === 304)时,它才会执行 dataType 转化是真的;否则,响应将传递给相应的处理程序。也就是说,如果请求失败,则不会根据预期的 dataType 解析响应。

I had a look into the jQuery ajax callback method. It does the dataType conversion only if ( status >= 200 && status < 300 || status === 304 ) is true; otherwise the response is passed, as such, to the corresponding handler. That is, if the request is a failure then the response is not parsed as per the expected dataType.

如果你想了解更多信息,你可以在jquery.js文件中查找上述条件,看看它是否正常工作。

If you want more info you can look for the above condition in the jquery.js file and see it working.

这篇关于jquery ajax在失败时不解析json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆