Jquery and php are combined to implement AJAX LongPoll and jquerylongpoll

Source: Internet
Author: User

Jquery and php are combined to implement AJAX LongPoll and jquerylongpoll

HTTP is a stateless, one-way protocol. Users can send requests to the server through the client and send a response by the server. To implement instant messaging applications such as chat rooms, WEBQQ, online customer service, and email, the "server push technology (Comet)" is required )".

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

<Div id = "msg"> </div> <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.

$ (Function () {$ ("# btn "). bind ("click", {btn: $ ("# btn")}, function (evdata) {$. ajax ({type: "POST", dataType: "json", url: "data. php ", timeout: 80000, // ajax request timeout time 80 seconds data: {time:" 80 "}, // after 40 seconds, no matter the result server returns data success: function (data, textStatus) {// obtain data from the server, display the data, and continue to query if (data. success = "1") {$ ("# msg "). append ("<br> [with data]" + data. text); evdata. data. btn. click ();} // if (data. success = "0") {$ ("# msg "). append ("<br> [no data]"); evdata. data. btn. click () ;}}, // Ajax request timeout, continue to query error: function (XMLHttpRequest, textStatus, errorThrown) {if (textStatus = "timeout ") {$ ("# msg "). append ("<br> [timeout]"); evdata. data. btn. click ();}}});});});

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)

If (emptyempty ($ _ POST ['time']) exit (); set_time_limit (0); // infinite request timeout time $ I = 0; while (true) {// sleep (1); usleep (500000); // 0.5 seconds $ I ++; // if data is obtained, the data is immediately returned to the customer service end, and end this request $ rand = rand (1,999); if ($ rand <= 15) {$ arr = array ('success '=> "1 ", 'name' => 'xiaocai ', 'text' => $ rand); echo json_encode ($ arr); exit ();} // After the server ($ _ POST ['time'] * 0.5) seconds, notify the customer service that there is no data if ($ I ==$ _ POST ['time']) {$ arr = array ('success' => "0", 'name' => 'xiaocai ', 'text' => $ rand); echo json_encode ($ arr ); exit ();}}

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.


Related Article

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.