Ajax long Polling (Longpoll) _php tutorial based on jquery and PHP

Source: Internet
Author: User
Tags vars
The traditional Ajax polling method, the customer service side at the user-defined time interval to the server to query the latest data. This kind of pull data takes a short time interval to ensure the accuracy of the data, but too short a time interval client sends multiple requests to the server in a short period of time.

Reverse Ajax, which is called long polling or comet. The server and customer service need to maintain a long-time request, which allows the server to return messages to the client when there is data.

Xhtml

 
  
  
  1. < Div id="msg"> div >
  2. < input id="btn"type="button" value="Test"/>

Jquery

This uses Ajax to request the data.php page to get the value of ' success ', requesting a time of 80 seconds. In these 80 seconds, if no return from the server ' success ' is kept in a connected state until there is a data return or ' success ' value of 0 to close the connection. The next request continues after the connection is closed.

 
 
  1. $ (function() {
  2. $ ("#btn"). Bind ("click", {btn:$ ("#btn")}, function(evdata) {
  3. $.ajax ({
  4. Type: "POST" ,
  5. DataType: "JSON" ,
  6. URL: "data.php" ,
  7. timeout:80000, //ajax Request Time-out time 80 seconds
  8. data:{time:"i"}, ///40 seconds after data is returned regardless of the result server
  9. Success: function (data,textstatus) {
  10. //Get data from the server, display the data and continue querying
  11. if (data.success=="1") {
  12. $ ("#msg"). Append ("
    [With Data] "+data.text);
  13. Evdata.data.btn.click ();
  14. }
  15. //did not get data from the server, continue to query
  16. if (data.success=="0") {
  17. $ ("#msg"). Append ("
    [No data] ");
  18. Evdata.data.btn.click ();
  19. }
  20. },
  21. //ajax Request timed out, continue querying
  22. Error: function (xmlhttprequest,textstatus,errorthrown) {
  23. if (textstatus=="Timeout") {
  24. $ ("#msg"). Append ("
    [Timeout] ");
  25. Evdata.data.btn.click ();
  26. }
  27. }
  28. });
  29. });
  30. });

Php

Here is the infinite loop, the end condition of the loop is to get the return result to return the JSON data.

and accept the $_post[' time ' parameter to limit the cycle timeout and avoid excessive waste of resources. (browser close will not send a message to the server, use may have been looped down)

 
 
  1. if (emptyempty($_post[' time '])) Exit ();
  2. set_time_limit (0); //Unlimited Request time-out
  3. $i = 0;
  4. while (true) {
  5. //sleep (1);
  6. Usleep (500000); //0.5 sec
  7. $i ++;
  8. //If the data is available, return the data to the customer service immediately and end the request.
  9. $rand =rand (1,999);
  10. if ($rand<=15) {
  11. $arr = Array (' success '= '1',' name '='xiaocai ' ,' text '=$rand);
  12. Echo Json_encode ($arr);
  13. Exit ();
  14. }
  15. //server ($_post[' time ']*0.5) seconds to tell the customer service end no data
  16. if ($i= =$_post[' time ']) {
  17. $arr = Array (' success '= '0',' name '= = ' Xiaocai ' , ' text ' = $rand );
  18. Echo Json_encode ($arr);
  19. Exit ();
  20. }
  21. }

Run effect: In the graph can see the request time of no data reached 40S, in the request of 40S to obtain the data request closes.


http://www.bkjia.com/PHPjc/445814.html www.bkjia.com true http://www.bkjia.com/PHPjc/445814.html techarticle The traditional Ajax polling method, the customer service side at the user-defined time interval to the server to query the latest data. This kind of pull data takes a short time interval to guarantee the data ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.