how to update content automatically without reloading webpage using php/ajax?

前端 未结 3 1749
清酒与你
清酒与你 2021-01-14 04:04

I\'m trying to create an auction tool using PHP. The problem I\'m having (and I appreciate its a basic one but I need clarification) is that I don\'t understand how to updat

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 04:30

    Ther question you asked has so much possible answers, they could fill a whole book.

    The simplest way to do this is to make an ajax call every few seconds using a combination of the setInterval() function and AJAX calls. You basically make an AJAX request every few seconds:

    setInterval(function(){
    $.get( "anyChanges.php", function( data ) {
      //do something with the returned data. Maybe update a table or something
    });
    }, 3000);
    

    On server side anyChanges.php returns some data immediately, like confirmation that something has changed and the new data.

    Long polling is how Google and others do it. It's the same as the example above. The difference is on the server side. anyChanges.php would not return immediately, the script would keep the connection open until there is some new changes and return them. If you use long polling, you usually set the interval to longer, for example 30 seconds.

    The best way to do it in my opinion, are WEB Sockets. It is a very new technology. With web sockets you can create a two-way connection to the server. That means that the server could simply send data to the clients without them having to ask for new data every few seconds. In PHP it's a little difficult to use web sockets (Or so I heard), but you could give it a shot. If you choose web sockets, try to learn about them first: tutsplus tutorial

    This library will be helpfull: socketo.me

提交回复
热议问题