Implement LongPoll Based on jQuery and PHP)

Source: Internet
Author: User

In the traditional AJAX round-robin mode, the customer service end queries the latest data on the server at a user-defined interval. This data pulling method requires a short time interval to ensure data accuracy. However, the customer service end sends multiple requests to the server within a short time interval.

Reverse AJAX is called long polling or COMET. The server and the client need to maintain a long request so that the server can return a message to the client when there is data.

XHTML

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

JQuery

Here, we use AJAX to request the data. php page to obtain the 'success' value. The request time reaches 80 seconds. If 'success 'is not returned from the server during the 80 seconds, the connection remains established until data is returned or the value of 'success' is 0. The next request is continued 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 timeout time 80 seconds
  8. Data: {time: "80"}, // after 40 seconds, no matter the result server returns data
  9. Success: function (data, textStatus ){
  10. // Obtain data from the server, display the data, and continue querying
  11. If (data. success = "1 "){
  12. $ ("# Msg"). append ("<br> [with data]" + data. text );
  13. Evdata. data. btn. click ();
  14. }
  15. // If no data is obtained from the server, continue to query
  16. If (data. success = "0 "){
  17. $ ("# Msg"). append ("<br> [no data]");
  18. Evdata. data. btn. click ();
  19. }
  20. },
  21. // The Ajax request times out and the query continues.
  22. Error: function (XMLHttpRequest, textStatus, errorThrown ){
  23. If (textStatus = "timeout "){
  24. $ ("# Msg"). append ("<br> [timeout]");
  25. Evdata. data. btn. click ();
  26. }
  27. }
  28. });
  29. });
  30. });

PHP

Here is an infinite loop, and the end condition of the loop is to get the returned result and return Json data.

In addition, the $ _ POST ['time'] parameter is used to limit the cycle timeout to avoid excessive resource waste. (When the browser is closed, messages will not be sent to the server, and the usage may keep repeating)

 
 
  1. If (emptyempty ($ _ POST ['time']) exit ();
  2. Set_time_limit (0); // unlimited request timeout
  3. $ I = 0;
  4. While (true ){
  5. // Sleep (1 );
  6. Usleep (500000); // 0.5 seconds
  7. $ I ++;
  8. // If data is obtained, the system immediately returns the data to the customer service end and ends 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. // After the server ($ _ POST ['time'] * 0.5) seconds, the server notifies the customer service that there is 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. }

Running effect: the figure shows that the request time without data reaches 40 S, and the request is closed if data is obtained in 40 S.


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.