在回调中进行回调

时间:2017-02-20 15:34:49

标签: javascript jquery ajax callback

我遇到异步操作问题。我需要知道我的表何时生成。但该表是根据通过ajax获取的数据库中的信息生成的。

这将是我的起点,我需要知道数据被取出并生成表格:

generateTable(function(r){

});

这里我从DB获取信息并将它们发送到回调函数

function getRepairBook(callback) {
            $.ajax({
                method: "GET",
                dataType: "json",
                contentType: "application/json",
                url: "x",
                success: function(response){
                    callback(response);
                },
                error: function(response){

                }
            });
        }

这里我需要回调函数的回调。但我不知道如何做到这一点:

function generateTable(callback) {

//callback of AJAX
   getRepairBook(function (response) {  //, callback

     console.log(response);
     $('#repTable >tbody').html("");

     var trHTML = '';
     $.each(response, function (i, item) {

       //...
       //build table
     });
     $('#repTable >tbody').append(trHTML);
     //need a callback of this callback function
     //callback();
   });

   callback();
}

2 个答案:

答案 0 :(得分:0)

试试这个

function getRepairBook(callback) {
            $.ajax({
                method: "GET",
                dataType: "json",
                contentType: "application/json",
                url: "x",
                success: function(response){
                    callback(response);
                    generateTable(response);//calling this on success of ajax call
                },
                error: function(response){

                }
            });
        }

答案 1 :(得分:0)

您可以链接JQuery deferred个对象。 他们以这种方式工作:



load success!

function foo() {
  // initialize the deferred
  var dfd = $.Deferred();
  
  // resolve the deferred after 2 sec
  setTimeout(function() {
    dfd.resolve();
  }, 2000);
  
  // return the promise
  return dfd.promise();
}

function bar() {
  var dfd = $.Deferred();  
  // resolve the deferred after 1 sec
  setTimeout(function() {
    dfd.resolve();
  }, 1000);
  return dfd.promise();
}

$(function() {      
  var dfd = foo();
  // when foo has been resolved
  dfd.then(function() {
    alert('foo has been resolved');
    var dfd2 = bar();
    // when bar has been resolved
    dfd2.then(function() {
      alert('bar has been resolved');
    });
  });
  
});




$ .ajax调用返回一个promise,因此您可以使用下一个要执行的操作/函数链接此promise的解析。