我的网络提供商是Strato。 我想每10秒钟进行一次mysql选择查询,而无需重新加载页面:
Strato无法使用Websocket。 对我来说替代方法是ajax轮询。 我尝试过:
$.ajax({
type: "POST",
url: "ajax/mysqlQuery.php",
data: 'userID=10'
}).done(function(result) {
if(result) {
// DO SOMETHING
}
})
mysqlQuery.php
<?php
$data= null;
include("../inc/config.php");
while(!$data) {
sleep(10);
$statement = $mysqli->prepare("SELECT * FROM `table` WHERE userID = ?");
$statement->bind_param("s", $_POST["userID"]);
$statement->execute();
$result = $statement->get_result();
while($row = $result->fetch_object()) {
$data[] = array("ID" => $row->ID);
}
}
echo json_encode($data);
?>
这很好用。 但是:
Strato的php max_execution_time为120秒。 我的脚本工作了120秒,反复无常-然后停止了。
我该如何解决这个问题?
答案 0 :(得分:1)
我在您的JS代码中看不到任何实际的轮询,例如不是setInterval
或类似的东西。要每10秒实际运行JS函数,您需要执行以下操作:
const doRequest = () => {
$.ajax({
type: "POST",
url: "ajax/mysqlQuery.php",
data: 'userID=10'
}).done(function(result) {
if (result) {
// DO SOMETHING
}
});
}
setInterval(doRequest, 1000);
关于PHP部分,我认为脚本中不需要while(!$data){ ... }
,因为只有在进行AJAX调用时才会对其进行评估,因此您实际上可以摆脱它。
我已经在您的PHP代码中修改了一些内容,我将对此进行解释
<?php
// just leave it alone at the beginning
include("../inc/config.php");
$statement = $mysqli->prepare("SELECT * FROM `table` WHERE userID = ?");
$statement->bind_param("s", $_POST["userID"]);
$statement->execute();
$result = $statement->get_result();
$data = null;
// maybe you can use $result->fetch_assoc() directly instead of returning an object and mapping it back to an associative array
while($row = $result->fetch_object()) {
$data[] = array("ID" => $row->ID);
}
// close the statement for better PHP performances
$statement->close();
// return it
echo json_encode($data);
?>
如果您的脚本将继续花费2分钟以上的时间来回答,则可能是数据库有问题,或者仅仅是托管服务器在限制您的脚本
作为旁注
如果您希望从PHP代码中得到一个数组,还可以将$data = []
设置为默认值,因此,如果未返回任何内容,则无需编辑JS代码中的内容,例如,检查结果是否实际上是数组等等...