2014-06-17 28 views
0

我在PHP中使用for循環,使用Jquery庫在JavaScript中使用Ajax調用。我的問題是,我想在每個PHP循環後更新頁面。現在等待10秒鐘,之後,向我顯示頁面。我想要一行一行地實時顯示。使用PHP和AJAX頁面更新的Jquery

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> 
+1

你是什麼意思「實時顯示,一行一行」? – ewizard

+0

我的data.php必須顯示十行,每行之後一秒。現在...我的index.php,10秒後顯示我所有的線。我希望每一秒都用當前行更新。 –

+0

順便說一句,你的'setTimeout'可能不像你期望的那樣工作。當你將它傳遞給超時時,你正在調用'ajaxCall',它應該是'setTimeout(ajaxCall,1000);'。這實際上會延遲執行1秒。 – christian314159

回答

0

你基本上要執行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>"; 
?> 
0

在你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> 
+0

謝謝! 我用@Parkyprg解決方案解決了問題,但用setInterval代替setTimeout。它像一個魅力。謝謝你們! –

相關問題