【问题标题】:JQuery ajax stoppen in $.when when server returns 500 error当服务器返回 500 错误时,JQuery ajax 在 $.when 中停止
【发布时间】:2016-07-10 13:24:36
【问题描述】:

我使用 JQuery 和 $.when 方法向服务器发出请求。

  $.when(ajaxRequest(param)).done(function(response){
    console.log(responseData);
  });

我的 ajax 函数如下所示:

function ajaxRequest(param){
  var requestedData;
  return $.ajax({
    type: 'POST',
    url: myurl,
    data: {
        setParam:param
    },
    error: function(data){
      console.log(data);
      return(data);
    }
  });
}

如果服务器返回 200 OK,一切正常。但是如果出现问题,服务器会回复 500。如何将响应正文返回给调用方法?

在ajaxRequest方法上用console.log打印errorbody,但没有返回给调用方法?

【问题讨论】:

  • .done()之后添加.fail()处理程序
  • @ArunPJohny 感谢您的提示!成功了!

标签: javascript jquery ajax .when


【解决方案1】:

在问题$.when() 给定js 是不必要的,因为$.ajax() 返回一个jQuery 承诺对象。 var requestedData; 未设置为值,将是 undefined .done();使用在.then().done() 提供的response 作为返回数据; .then() 处理成功和错误响应

function ajaxRequest(param){
  return $.ajax({
    type: 'POST',
    url: myurl,
    data: {
      setParam:param
    }
  });
}

ajaxRequest(param)
.then(function(response){
  console.log(response);
  return response
}
// handle errors at second function of `.then()`
, function err(jqxhr, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);
  return errorThrown;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2019-11-12
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多