1
我試着做一個基本的while循環javascritp,但我發現在OS X中的車輪圖標每次我啓動我的腳本。當我按下一個HTML按鈕執行該代碼:while循環使用Ajax調用不工作在JavaScript
<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循環,但我無法得到它的工作。
我需要再等5分鐘才能接受您的答案,但它已解決了我的問題,非常感謝! – user3033437