在重复的jQuery/Ajax函数中设置延迟

Jer*_*oen 11 javascript ajax jquery

我试图为可重复的查询添加延迟.

我发现.delay不是在这里使用的.相反,我应该使用setInterval或setTimeout.我试过了两个,没有任何运气.

这是我的代码:

<?php 
include("includes/dbconf.php");

$strSQL = mysql_query("SELECT workerID FROM workers ORDER BY workerID ASC");
while($row = mysql_fetch_assoc($strSQL)) {
?>
<script id="source" language="javascript" type="text/javascript">

  $(setInterval(function ()
  {
    $.ajax({                                      
      cache: false,
      url: 'ajax2.php',        
      data: "workerID=<?=$row['workerID'];?>",
      dataType: 'json',    
      success: function(data)
      {
        var id = data[0];              //get id
        var vname = data[1];           //get name
        //--------------------------------------------------------------------
        // 3) Update html content
        //--------------------------------------------------------------------
        $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
      } 
    });
  }),800); 

  </script>
<?php
}
?>
<div id="output"></div>
Run Code Online (Sandbox Code Playgroud)

代码工作正常,它按要求输出结果.它只是没有延迟的负载.时间和/或间隔似乎不起作用.

谁知道我做错了什么?

Chr*_*pen 25

我永远不明白为什么人们总是间隔地添加他们的AJAX请求,而不是让成功的AJAX调用只是自己调用,同时冒着严重的服务器负载通过多个请求而不仅仅是在你成功回来后再打电话.

有鉴于此,我喜欢编写解决方案,其中AJAX调用只是在完成时调用自己,如:

// set your delay here, 2 seconds as an example...
var my_delay = 2000;

// call your ajax function when the document is ready...
$(function() {
    callAjax();
});

// function that processes your ajax calls...
function callAjax() {
    $.ajax({
        // ajax parameters here...
        // ...
        success: function() {
            setTimeout(callAjax, my_delay);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

我希望这是有道理的!:)

更新:

在再次审阅之后,我注意到原始问题中的PHP代码中也存在一个问题,我需要澄清和解决.

虽然上面的脚本在创建AJAX调用之间的延迟方面效果很好,但是当添加到原始帖子中的PHP代码时,脚本将只会出现echo与SQL查询选择的行数一样多的次数,从而创建多个函数.相同的名称,可能同时进行所有AJAX调用......根本不是很酷......

考虑到这一点,我提出了以下附加解决方案 - array使用PHP脚本创建一个可以由JavaScript一次消化的元素,以实现所需的结果.首先,PHP构建JavaScript数组字符串......

<?php 
    include("includes/configuratie.php");
    $strSQL = mysql_query("SELECT workerID FROM tWorkers ORDER BY workerID ASC");

    // build the array for the JavaScript, needs to be a string...
    $javascript_array = '[';
    $delimiter = '';
    while($row = mysql_fetch_assoc($strSQL))
    {
        $javascript_array .= $delimiter . '"'. $row['workerID'] .'"'; // with quotes
        $delimiter = ',';
    }
    $javascript_array .= ']';
    // should create an array string, something like:
    // ["1","2","3"]
?>
Run Code Online (Sandbox Code Playgroud)

接下来,JavaScript来消化和处理我们刚创建的数组......

// set your delay here, 2 seconds as an example...
var my_delay = 2000;

// add your JavaScript array here too...
var my_row_ids = <?php echo $javascript_array; ?>;

// call your ajax function when the document is ready...
$(function() {
    callAjax();
});

// function that processes your ajax calls...
function callAjax() {
    // check to see if there are id's remaining...
    if (my_row_ids.length > 0)
    {
        // get the next id, and remove it from the array...
        var next_id = my_row_ids[0];
        my_row_ids.shift();
        $.ajax({
            cache    : false,
            url      : 'ajax2.php',
            data     : "workerID=" + next_id, // next ID here!
            dataType : 'json',
            success  : function(data) {
                           // do necessary things here...
                           // call your AJAX function again, with delay...
                           setTimeout(callAjax, my_delay);
                       }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你知道吗?我比我的答案更喜欢这个。+1 (2认同)
  • 在块中使用此方法COMPLETE也很好. (2认同)