以下代码的目的是使用Ajax重复获取PHP查询结果,直到结果为" 6"。
正在接受该脚本继续运行" 6"当我的CPU风扇开始大声咆哮时收到,并在几秒钟之后,"正在加载..."消息开始闪烁。
想法?
function refreshData(){
var display = document.getElementById("content");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "get_status.php");
//xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
display.innerHTML = this.responseText;
var test_response = this.responseText;
} else {
display.innerHTML = "Loading...";
};
if (this.responseText != "6") {
refreshData();
}
}
}
这是PHP代码:
<?php
$dbconn = pg_connect("host=localhost dbname=postgres user=postgres password=kevin234") or die('Could not connect: ' . pg_last_error());
set_time_limit(0);
$result = pg_query('select max(num_files), max(file_num) from status');
$num_files = pg_fetch_row($result);
echo "max_file_num = " . $num_files[1];
?>
从此代码中调用refreshData():
var upload = function(files) {
var formData = new FormData(),
xhr = new XMLHttpRequest(),
x;
xhr.upload.addEventListener("progress", progressHandler, false);
//xhr.addEventListener("load", refreshData, false);
//xhr.addEventListener("error", errorHandler, false);
//xhr.addEventListener("abort", abortHandler, false);
for(x = 0; x < files.length; x = x +1) {
formData.append('file[]', files[x]);
}
xhr.onload = function() {
var data = JSON.parse(this.responseText);
displayUploads(data);
}
xhr.open('post', 'ids_v0.00_progress_bar.php');
xhr.send(formData);
function progressHandler (event) {
document.getElementById("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
if (event.loaded = event.total) {
refreshData();
}
}
}
答案 0 :(得分:3)
正在接受脚本继续运行&#34; 6&#34;
的结果
您需要在onreadystatechange
调用的xmlhttp
成功内移动重新调用该函数。这样,一次发送一个请求,而不是数百个。
function refreshData() {
var display = document.getElementById("content");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "get_status.php");
//xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
display.innerHTML = this.responseText;
var test_response = this.responseText;
if (this.responseText != "6") {
refreshData();
}
} else {
display.innerHTML = "Loading...";
};
}
}
&#13;
为什么要更改
您的代码存在的问题是,无论responseText
值如何,您的网站都会继续发送请求。 responseText != "6"
唯一要做的就是检查请求的实例是否应该发送另一个。当一个请求完成时,即在if(this.readyState === 4 && this.status === 200)
中,必须发生有条件的重新发送请求。