从数据库中获取数据并不断更新网页

时间:2019-01-23 14:23:59

标签: javascript jquery

我要做的就是从数据库中获取一个字符串并将其显示在我的网站上,但是要不断刷新它。这是一个朋友快速为我编写的代码,但是我对此一无所知,他不在这里帮助我,我需要在今晚之前完成。

查询只是
$ sql =“从灯选择状态”; $ result = $ conn-> query($ sql);

我知道这应该很容易,但是我真的不知道。谢谢分配!

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>

1 个答案:

答案 0 :(得分:0)

对于您的网页,可以使用:

<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;