Fetch data from database and update webpage continuously

扶醉桌前 提交于 2021-02-20 02:58:09

问题


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.

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>

回答1:


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>

And for the form.php something along the lines of:

$conn = new mysqli connection
$sql = "SELECT status FROM light"; 
$result = $conn->query($sql);
echo $result;


来源:https://stackoverflow.com/questions/54329387/fetch-data-from-database-and-update-webpage-continuously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!