我想根据值动态更改我的网站。我从我的MySQL数据库中检索数据,并希望更改尽可能接近实时。我有一些代码可以在某种程度上做我想做的事情,但是值的更新似乎失败了,起初它可以工作,然后在几次调用之后,它似乎只是在两个值之间随机切换。根据MySQL数据库值动态更改网站内容
我有三个php页面,一个从数据库(database.php)中获取值,另一个根据数据库值(response1.php和response2.php)生成响应。我不认为这些页面是问题的一部分,因为我已经检查过它们返回值并返回我想要的值。项目的第二部分(以及可能失败的地方)是我的主页面(如下)。我不确定我是否选择了最好的技术来解决我的问题,或者是否有更好的方法来解决问题。
<html>
<head>
<script type="text/javascript">
var databaseanswer, xmlhttp;
function databasecheck() {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "database.php", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
databaseanswer = xmlhttp.responseText;
document.getElementById("database").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.send();
}
function response() {
if (databaseanswer == "No Tag") {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "response1.php", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.send();
}
else {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "response2.php", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.send();
}
}
setInterval(databasecheck, 1800);
setInterval(response, 2000);
</script>
</head>
<body>
<p> this is a test site </p>
<p> response from server: </p>
<div id="response">
</div>
<p> answer from database: </p>
<div id="database">
</div>
</body>
</html>
好了,这是我的编辑代码:
<html>
<head>
<script>
function database(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","responsedatabase.php",false);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("database").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send();
}
setInterval(database,1000);
</script>
</head>
<body>
<p>answer from database: </p><div id="database"></div>
</body>
</html>
你应该研究一下'jQuery's'' AJAX'的功能:http://api.jquery.com/jQuery.ajax/ –
'if(databaseanswer ==“No Tag”){'没有任何意义,或任何 – samayo
基本上“无标签”是我的数据库中的默认值。 – nerq