我想在从同一页面的另一个实例更新数据库时更新我的页面。但我做不到。索引.php是我的主页。doo() 函数的 if 块,if(x.readyState==4 && x.status==200)从不执行,可能是因为状态永远不会等于 200。在控制台中,我收到"1000 无法加载资源:net::ERR_INSUFFICIENT_RESOURCES"。此外,我不明白为什么更新功能不等待 10 秒并溢出堆栈。我将非常有义务获得任何解决方案和建议。
索引.php
<html>
<head>
<title>das shuler
</title>
<script>
function foo()
{
//if (str.length==0) {
//document.getElementById("txtHint").innerHTML="";
//return;
//else {
data=document.getElementById("story").value;
alert(data);
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert("state change");
data=xmlhttp.responseText;
parent=document.getElementById("content");
child=document.createElement("div");
news=document.createTextNode(data);
child.appendChild(news);
parent.appendChild(child);
id=setTimeout(update(data),20);
alert("after setTimeout");
//document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
alert("data sent");
xmlhttp.open("GET","populate.php?story="+data,true);
xmlhttp.send();
}
function update(str)
{
data=str;
//alert(data);
//alert("inside update");
var x=new XMLHttpRequest();
x.onreadystatechange=doo();
function doo(){
if(x.readyState==4 && x.status==200)
{
alert("here");
data=x.responseText;
if(data!=str)
{
parent=document.getElementById("content");
child=document.createElement("div");
news=document.createTextNode(data);
child.appendChild(news);
parent.appendChild(child);
}
}
x.open("GET","retrieve.php",true);
x.send()
id=setInterval(update(data),10000);
}
}
</script>
</head>
<body onload="update()">
<div id="header"><h1 style="color:grey;align:center;">das shuler</h1><hr></div>
<div id="content">
</div>
<div id="make-content"><form method="post" action="populate.php"><input type="text" name="story" id="story"><input type="button" value="post" onclick="foo()"></form></div>
</body>
填充.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$data=$_REQUEST["story"];
echo $data;
$sql = "INSERT INTO News (Data)
VALUES ('$data')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
// echo "New record created successfully. Last inserted ID is: " . $last_id;
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
检索.php
<?php
$conn=mysqli_connect("localhost","root","root","myDB");
echo "hrloo";
$sql="select Data from News ";
$q=mysqli_query($conn,$sql);
$data=mysqli_fetch_assoc($q);
echo $data;
mysqli_close($conn);
?>
您的代码似乎已损坏。setTimeout 函数逻辑无法正常工作。setTimeout 之后的 alert() 将在页面加载时触发,因为它不包含在您设置超时的函数中。
此外,setTimeout() 以毫秒为单位需要时间。如果您需要在窗口上休息 10 秒,请尝试放置 10,000。
参考这个:
setTimeout(function(){ alert("after setTimeout"); },10000);