问题
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