javascript - JQuery ajax stoppen in $.when 服务器返回 500 错误

标签 javascript jquery ajax .when

我使用 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。我如何将响应主体返回给调用方法?

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

最佳答案

问题 $.when() 中给出的 js 不是必需的,因为 $.ajax() 返回一个 jQuery promise 对象。 var requestedData; 未设置为值,将在 .done() 处为 undefined;使用 .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;
});

关于javascript - JQuery ajax stoppen in $.when 服务器返回 500 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36175033/

相关文章:

php - 选择选项后不显示数据

asp.net - ajax + comet + asp.net 是否可扩展?

javascript - 试图让 scrollTo 水平工作

javascript - 从 AJAX 成功函数更新图像源

javascript - jqGrid 无法在 Chrome/Chrome Frame 中正确呈现

jQuery .load(),在图像加载之前不显示新内容

javascript - 日期转换问题(从 JS -> .NET 像字符串一样发送)

javascript - 如何在警报中显示 console.log 输出

javascript - 如何选择具有复杂 ID 的元素

javascript - 动态更改网页上的图像