簡體   English   中英

使用Ajax調用的while循環在javascript中不起作用

[英]while loop with ajax call not working in javascript

我試圖在javascritp中做一個基本的while循環,但是每次啟動腳本時,我都會在os x中得到wheel圖標。 當我按下html按鈕時,將執行以下代碼:

    <script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        myFunction();
        });
});
    var num=1;
function myFunction() {

    var c = 0;
    // Find a <table> element with id="myTable":
    var table = document.getElementById("myTable");
    // Create an empty <tr> element and add it to the 1st position of the table:
    var row = table.insertRow(-1);
    // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);

while(num != 5)
{
    $.ajax({
            type: 'get',
            url: 'controller/script.php',
            type: "POST",
            data: (
            {
                name: 'Alfro',
                surname: 'McDohl',
                num: num
            }),
            success: function(data) 
            {                
                $("p.polla").text(data);
                var result = $.parseJSON(data);
                // Add some text to the new cells:
                cell1.innerHTML = result[0];
                cell2.innerHTML = result[1];
                num = result[2];
            },
            error: function()
            {
                alert('error');
            },
        });
    }           
}

這是script.php的PHP代碼:

<?php

$name = $_POST['name'];  
$surName = $_POST['surname'];
$num=$_POST['num'];
$num++;
if ($_POST['num']>=10){
    echo json_encode(array($name.$c++, $surName.$c++,'0'));
}
else{
    echo json_encode(array($name.$c++, $surName.$c++,$num));
}
?>

這樣做的意思是因為我想從數據庫中加載數據,但是檢索所有信息花費了太多時間,所以我想通過ajax調用顯示一個結果,然后繼續檢索數據庫以顯示另一個結果, “一個一個”,為此,我需要使用while循環,因此我正在使用while循環,但是我無法使其正常工作。

不要使用while循環。 您的Ajax調用是異步發生的,因此while循環永遠不會更改n的值。 因此,刪除循環並將條件放入Ajax成功塊中,然后從那里再次調用myFunction(num)

success: function(data) 
            {                
                $("p.polla").text(data);
                var result = $.parseJSON(data);
                // Add some text to the new cells:
                cell1.innerHTML = result[0];
                cell2.innerHTML = result[1];
                num = result[2];
                myFunction(num);
            },

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM