简体   繁体   English

存在具有警报功能的回调被触发,并且没有警报就不会触发吗?

[英]Callback gets fired with an alert function is present and it not fire without an alert?

When the alert function is present (shown below), the callback function gets fired and everything works. 存在警报功能时(如下所示),将触发回调函数,并且一切正常。 When the alert function is not present, the callback function never gets fired. 如果不存在警报功能,则永远不会触发回调函数。

  function getTableData(tableName, startRow, endRow, callback)
  {
    CK.getData = $.getJSON("getTableData.php",{tN: tableName, sR: startRow, eR: endRow}, function(dataTable){});

    alert("test"); 
    CK.getData.done(function()
    {
       // load data inside table using an $.each function...
       callback(); // works only when the alert function above is present..
    });
  }

   getTableData(tableName, startRow, endRow, function()
   {
      $(".logTable").after($addRowData); 
   });

The problem was the ajax function is non-blocking (asynchronous), meaning the each loop continues on without waiting for a response. 问题在于ajax函数是非阻塞的(异步的),这意味着每个循环都继续进行而无需等待响应。 By the time you get a response from any of the getJSON call you've finished iteration. 到您从任何getJSON调用获得响应时,您就已经完成了迭代。

I wrap the ajax function within a closure: 我将ajax函数包装在一个闭包中:

  (function(tableName, startRow, endRow)
  { 
      getTableData(tableName, startRow, endRow, function()
      {
        $(".logTable").after($addRowData); 
      });

  })(tableName, startRow, endRow);

And set the async variable within $.ajax object to false for sync. 并将$ .ajax对象中的async变量设置为false进行同步。 communication. 通讯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM