按顺序延迟一段时间后在jquery中执行php文件

时间:2011-07-31 11:56:27

标签: php jquery ajax loops

我有一个jquery函数,我需要按照以下方式工作

1. call a php file
2. log the values return by php file
3. have time delay
      again repeat the above process for number of time

为此我写下了jquery和php文件

<script type="text/javascript">
$(document).ready(function() {
listsValues="1,10,20";
n=0;
msgids = listsValues.split(',');
$.each(msgids, function() {
html="TEST MESSAGE";
 n++;
setTimeout(function() {
$.ajax({
                type: "POST",
                url: "test1.php",
                cache:false,
                data:"id="+ msgids[n],
                dataType:'json',
                success: function(json)
                {
                var foo = json.foo;
                uemail = foo.split(',');
                console.log(uemail)
                }
            });
 }, 1000);

 });

  });
</script> 

这里是test1.php

<?php
$id=$_POST['id'];

$val="";
for($i=1;$i<=$id;$i++) { 

$val.=$i;

}

$return["foo"] =$val;

print stripslashes(json_encode($return));

?>

但当我执行此脚本时,这不是我想要的方式 我可以在firebug中看到test1.php文件执行(调用)3次,然后在控制台中写入值

as i said waht i want was
1. execute test1.php file
2. write value in console
3. give delay

then repeat

由于

1 个答案:

答案 0 :(得分:1)

我认为您正在搜索这样的内容:

<script type="text/javascript">
function request(n) {
    $.ajax({
        type: "POST",
        url: "test1.php",
        cache:false,
        data:"id="+ msgids[n],
        dataType:'json',
        success: function(json)
        {
            var foo = json.foo;
            var uemail = foo.split(',');
            console.log(uemail);
            setTimeout(
                function() { 
                    request(n);
                }
                , 1000
            );
        }
    });
}

$(document).ready(function() {
    var listsValues="1,10,20";
    var n=0;
    var msgids = listsValues.split(',');
    $.each(msgids, function() {
        var html="TEST MESSAGE";
        n++;
        request(n);
    });
});
</script>