繁体   English   中英

带有PHP和AJAX页面的jQuery更新

[英]Jquery with PHP and AJAX page update

我在PHP中有一个for循环,并在带有Jquery库的JavaScript中有一个Ajax调用。 我的问题是我想在每个php循环后更新页面。 现在等待10秒钟,然后显示该页面。 我想逐行实时显示。

data.php

 <?php

for($i=0;$i<10;$i++) {

echo "lorem ipsum" . "<br>";
sleep(1);

 }

  ?>

和index.php

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>


                function ajaxCall(){
                $.ajax({url:"data.php",success:function(result){
                    $("#div1").html(result);
                }});
            }


                setTimeout(ajaxCall(), 1000);

    </script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>

</body>
</html>

在您的data.php中,无需睡眠和循环。 循环将使用Javascript(带有setTimeout)完成。

因此data.php可能类似于:

 <?php

echo "lorem ipsum" . "<br>";

  ?>

并且您的index.php应该附加数据:

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>


                function ajaxCall(){
                $.ajax({url:"data.php",success:function(result){
                    $("#div1").append(result);
                }});
            }


                setTimeout(ajaxCall, 1000);

    </script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>

</body>
</html>

您本质上想执行10个页面更新,每个更新都基于服务器端php代码上循环的每次迭代进行一秒钟。 我建议您重新设计,以使循环发生在客户端,而在服务器端,您只需响应每个请求即可。 我认为这种方法很容易理解。

下面的客户端代码未经测试,并显示了方法(index.php)

//this is called 10 times, with i being the number of the call starting at 1
function ajaxCall(i){
  //note the query string parameter being passed to the php script
  $.ajax({url:"data.php?i="+i,success:function(result){ 
    $("#div1").html(result); 
    if(i<10){ //if we have not reached 10 calls, delay and then call again while  incrementing the count
      setTimeout(ajaxCall(i+1), 1000);
    }
  }
});

//make the first ajax call
setTimeout(ajaxCall(1), 1000);

在data.php中,您需要检查该查询字符串参数。 请注意,没有循环,服务器端代码也不再处于休眠状态。

<?php
$i = $_GET["i"];
//do something with $i which should be in the range 1-10 (you should check this)
echo "lorem ipsum " . $i . "<br>";
?>

暂无
暂无

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

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