当服务器返回500错误时,JQuery ajax在$.中停止

JQuery ajax stoppen in $.when when server returns 500 error

本文关键字:ajax JQuery 返回 服务器 错误      更新时间:2023-09-26

我使用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打印,但没有返回到调用方法?

问题$.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;
});