如何在函数中返回Ajax的值?

时间:2021-01-03 02:03:37

I have the function below. How can I return the values for success, error, complete in a function?

我有以下功能。如何在函数中返回成功,错误,完成的值?

function checkstatus() {
  $.ajax({
    url: "foo.json",
    beforeSend : function(jqXHR, settings) {
      console.info('in beforeSend');
      console.log(jqXHR, settings);
    },
    error : function(jqXHR, textStatus, errorThrown) {
      alert(" 500  data still loading"+ jqXHR +  " : " + textStatus +  " : " + errorThrown);
      console.info('in error');
      console.log(jqXHR, textStatus, errorThrown);
    },
    complete : function(jqXHR, textStatus) {
      alert(" complete "+ jqXHR +  " : " + textStatus);
      console.info('in complete');
      console.log(jqXHR, textStatus);
    },
    success: function(data, textStatus, jqXHR){
      alert(" success "+ jqXHR +  " : " + textStatus);
      console.info('in success');
      console.log(data, textStatus, jqXHR);
    }
  });
}

2 个解决方案

#1


0  

try something like:

尝试类似的东西:

function checkstatus( callback ) {
   $.ajax({
    .......
    success: function(data, textStatus, jqXHR){
        callback(data);
    }
   });
}
//and callback
checkstatus(function (data) {    
    alert(data);
});

#2


0  

You can't return the values from a separate function with an asynchronous request because the code after the .ajax call (where you would return) will execute before the ajax callbacks. Instead, you should create a dependency on the callback.

您不能使用异步请求从单独的函数返回值,因为.ajax调用之后的代码(您将返回的位置)将在ajax回调之前执行。相反,您应该在回调上创建依赖项。

If the request is synchronous, you could do this:

如果请求是同步的,您可以这样做:

function checkStatus() {
   var statuses = [];
   $.ajax(...
      success: function (data, textStatus, jqXHR) {
          statuses.push(textStatus);
      }
   ...

   return statuses;
}

#1


0  

try something like:

尝试类似的东西:

function checkstatus( callback ) {
   $.ajax({
    .......
    success: function(data, textStatus, jqXHR){
        callback(data);
    }
   });
}
//and callback
checkstatus(function (data) {    
    alert(data);
});

#2


0  

You can't return the values from a separate function with an asynchronous request because the code after the .ajax call (where you would return) will execute before the ajax callbacks. Instead, you should create a dependency on the callback.

您不能使用异步请求从单独的函数返回值,因为.ajax调用之后的代码(您将返回的位置)将在ajax回调之前执行。相反,您应该在回调上创建依赖项。

If the request is synchronous, you could do this:

如果请求是同步的,您可以这样做:

function checkStatus() {
   var statuses = [];
   $.ajax(...
      success: function (data, textStatus, jqXHR) {
          statuses.push(textStatus);
      }
   ...

   return statuses;
}