retrieving data from a database using ajax without requesting every x seconds

痴心易碎 提交于 2019-12-13 23:31:12

问题


I have been reading up on how to use XMLHTTPRequests to grab data from a database via JavaScript.

However, I have noticed that every single one of these "tutorials" use an interval to retrieve data every x seconds, and it seems like this would be extremely taxing (and unnecessary) on the server; especially considering sometimes these queries would return nothing at all.

So, how do websites such as Facebook and Twitter do it?

Because something like this (I'm using jQuery for simplicity):

setInterval(function(){ // retrieve data every 5 seconds
    $.ajax({
        url: "datagrab.php",
        success: function(data){
            $("body").append(data);
        }
    });
}, 5000);

... seems a bit over the top; especially if you have a fairly small server (or data cap) that is unable to make requests at that rate.

Cheers.


回答1:


You can use EventSource to constantly stream data to browser.

const source = new EventSource("data.php");
// note, you can also set custom event handlers for named events
source.addEventListener("message", function(e) {
  // do stuff with `e.data`
});
// close event stream
// source.close();

 <?php 
 header("Content-Type: text/event-stream\n\n"); 
 header("Cache-Control: no-cache"); 
 // get, do stuf with `$data1`, `$data2`
 echo "data: $data1\n";
 echo "data: $data2\n\n";


来源:https://stackoverflow.com/questions/42172172/retrieving-data-from-a-database-using-ajax-without-requesting-every-x-seconds

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