1 回答

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
我沒有在您的 JS 代碼中看到任何實(shí)際的輪詢,例如。不是setInterval那種東西。要每 10 秒實(shí)際運(yùn)行一次 JS 函數(shù),您應(yīng)該需要以下內(nèi)容:
const doRequest = () => {
$.ajax({
type: "POST",
url: "ajax/mysqlQuery.php",
data: 'userID=10'
}).done(function(result) {
if (result) {
// DO SOMETHING
}
});
}
setInterval(doRequest, 1000);
關(guān)于 PHP 部分,我認(rèn)為您的腳本中不需要 a while(!$data){ ... },因?yàn)橹挥性谶M(jìn)行 AJAX 調(diào)用時(shí)才會(huì)對(duì)其進(jìn)行評(píng)估,因此您實(shí)際上可以擺脫它。
我已經(jīng)修改了您的 PHP 代碼中的一些內(nèi)容,我將對(duì)此進(jìn)行解釋
<?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);
?>
如果您的腳本將繼續(xù)花費(fèi)超過 2 分鐘的時(shí)間來回答,則可能是數(shù)據(jù)庫(kù)出了問題,或者它只是限制了您的腳本的主機(jī)
作為旁注,如果您希望從您的 PHP 代碼中獲得一個(gè)數(shù)組,您也可以設(shè)置$data = []為默認(rèn)值,這樣如果沒有返回任何內(nèi)容,您將不需要在 JS 代碼中編輯內(nèi)容,例如檢查結(jié)果是否實(shí)際上是一個(gè)數(shù)組等等...
- 1 回答
- 0 關(guān)注
- 129 瀏覽
添加回答
舉報(bào)