从数据库中获取数据并不断更新网页 [英] Fetch data from database and update webpage continuously
本文介绍了从数据库中获取数据并不断更新网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要做的就是从数据库中获取一个字符串并将其显示在我的网站上,但让它不断刷新.这是一个朋友很快为我写的代码,但我真的对它一无所知,他不是来帮助我的,我需要在今晚之前完成.
All I want to do is fetch a string from a database and display it on my website but have it refresh continuously. This is the code a friend wrote for me quickly but I really don't know anything about it and he's not here to help me and I need to have it done by tonight.
查询只是
$sql = "SELECT status FROM light";$result = $conn->query($sql);
The query is just
$sql = "SELECT status FROM light";
$result = $conn->query($sql);
我知道这应该很容易,但我真的想不通.感谢分配!
I know it should be easy but I really can't figure it out. Thanks allot!
setInterval(function() {
// Variables
let URL = "/localhost/form.php";
let request = new XMLHttpRequest();
let response = null;
// Response
request.onreadystatechange = function() {
// Checks
if (request.readyState != 4) { return false }
if (request.status == 521) { response = null }
if (request.status == 520) { response = null }
if (request.status == 508) { response = null }
if (request.status == 500) { response = null }
if (request.status == 500) { response = null }
if (request.status == 403) { window.location.reload() }
if (request.status == 302) { response = null }
if (request.responseText) { response = request.responseText } else { response = null }
// USE THE VALUE OF response TO UPDATE THE PAGE
console.log("Server responded with:", response);
}
// Submit
request.open('GET', URL, true);
request.send(null);
}, 1001);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
setInterval(function() {
// Variables
let url = "/localhost/form.php";
// Get
$.get(url, function(d) {
// check if data (d) is valid
// update ui accordingly [Eg. $("#abc").text(d)]
console.log(d);
});
}, 1001);
</script>
推荐答案
对于您的网页可能使用:
For your webpage maybe use:
<body>
<div class='updatable'></div> // element in your page to display the text
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> // get hold of jquery
<script>
$(document).ready(function(){ //wait until page is ready
setInterval(function() { // this will execute the function every 1s
// Variables
let url = "form.php"; // locaiton of your form page
// Get
$.get(url, function(d) { // jquery function that 'does' the GET request
$('.updatable').text(d) // when we have a returned request, populate the element above with the body of the returned request ( plain text )
});
}, 1000); // here we have set 1s (1000 ms)
})
</script>
</body>
对于 form.php
类似的东西:
$conn = new mysqli connection
$sql = "SELECT status FROM light";
$result = $conn->query($sql);
echo $result;
这篇关于从数据库中获取数据并不断更新网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文