【问题标题】:How to read a property from a JSON response when the HTTP response has a failure code?当 HTTP 响应有失败代码时,如何从 JSON 响应中读取属性?
【发布时间】:2015-02-01 09:10:36
【问题描述】:

我有这个代码:

$.post(Routing.generate('parMarcaModelo'), {
    "marcaId": currBranch,
    "modeloId": currModel,
    "marcaNombre": currBranchName,
    "modeloNombre": currModelName
}, 'json').done(function (data, textStatus, jqXHR) {
    // do something here
}).fail(function (jqXHR, textStatus, errorThrown) {
    // Catch error from server and logs to console
    var err = eval("(" + jqXHR.responseText + ")");
    colose.log('Error', err.Message, 20000);

    return false;
});

服务器端返回一个像这样的 JSON:

{
   "success":false,
   "error":"El par Marca2-Modelo1 ya existe. Por favor escoja otra combinaci\u00f3n.",
}

但也会返回 400 代码,因此 Ajax 调用将通过 .fail() 回调插入 .done()。有了这些信息,我如何从 .fail() 中的 JSON 中捕获 error 键以显示给用户?

我找到了这段代码:

$.get('http://localhost/api').then(function(res) {
    var filter $.Deferred()

    if (res.success) {
        filter.resolve(res.data)
    } else {
        filter.reject(res.error)
    }

    return filter.promise()
}).done(function(data) {
    console.log('Name:',  data.name) // Outputs: Foo
}).fail(function(error) {
    console.log('Error:', error) // Outputs: Something bad happened.
})

关于 SO 的 this 主题,但不知道是否正确以及是否会以某种方式影响我的代码。

有什么帮助或建议吗?

【问题讨论】:

  • 如果你得到 JSON,你就在 done() 方法中
  • 如果邮件地址是err.error,你为什么要访问err.Message呢?你为什么要使用eval() 来解析你的 JSON?
  • ...您所说的“抓住”error 键是什么意思?你是在抛出一个错误,或者这只是对 catch 这个词的不幸使用,它具有非常特殊的含义?
  • @squint 我从某个地方得到该代码并且未经测试只是对我很好奇它应该如何工作以修改和适应我的环境,应该是 err.error 如你所说?对于catch,我的意思是当服务器端出现任何故障时,我会向 Ajax 请求发送400 响应,并且还会将应用程序的通用消息作为 Json 发送,但我很确定这将是来自Ajax、jQuery、jqXHR 方面,我说得对吗?我需要捕获所有这些,来自 400 响应的 JSON 和来自 jqXHR 的,为什么?
  • 如果我理解正确,更清晰的标题可能是“当 HTTP 响应有失败代码时如何从 JSON 响应中读取属性?”

标签: javascript jquery ajax json jqxhr


【解决方案1】:

您将'json' 作为成功回调函数发送到$.post()

这是正确的函数签名: jQuery.post( url [, data ] [, success ] [, dataType ] )


澄清

此代码将起作用,因为它传入一个空函数来代替“成功”。

$.post('rest.php', {data : 'data'}, function(){},'json').done(
function (data, textStatus, jqXHR) {
    // do something here
}).fail(function (jqXHR, textStatus, errorThrown) {
    // Catch error from server and logs to console
    console.log('Error', jqXHR.responseJSON, 20000);

    return false;
});

但是,此代码不会:

$.post('rest.php', {data : 'data'}, 'json').done(
function (data, textStatus, jqXHR) {
    // do something here
}).fail(function (jqXHR, textStatus, errorThrown) {
    // Catch error from server and logs to console
    console.log('Error', jqXHR.responseJSON, 20000);

    return false;
});

为了证明,请查看jQuery source code 中的第 781-798 行。如果data 参数是一个函数,例如success 回调,项目将被转移。但是,由于情况并非如此,因此每个参数都将按照它们在函数中出现的位置放入。

在第二个版本中,Ajax.succees 将设置为字符串 'json'Ajax.dataType 设置为 undefined。该版本的jqXHR.responseJSON 将返回undefined,因为它没有被解析为JSON。

然而,第一个版本返回一个 JSON 对象。


另外,您在代码中写了 colose.log 而不是 console.log。这可能是无法获取数据的原因。

【讨论】:

  • [, ...] 表示可选。
  • return false; 没用
  • 所以这是我应该走的路? @epascarello 为什么?因为回调通过.fail() 本身就失败了?
  • 为什么?因为你不能从异步方法返回。
  • @squint 我用源代码编辑了我的答案以解释我的意思。其他:我宁愿使用 jQuery 中的 $ajax 函数以更简洁的方式创建此功能,但我尽量不要过多地更改原始代码。这就是为什么我也没有删除return false;,我知道这没用。
猜你喜欢
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-03
  • 2019-02-04
  • 1970-01-01
  • 2017-02-27
  • 2022-06-28
  • 1970-01-01
相关资源
最近更新 更多