31 Mayıs 2011 Salı

javascript ajax long polling- with jQuery

Specific methods of implementing Comet fall into two major categories: streaming and long polling.

Streaming

An application using streaming Comet opens a single persistent connection from the client browser to the server for all Comet events. These events are incrementally handled and interpreted on the client side every time the server sends a new event, with neither side closing the connection.[3]

Specific techniques for accomplishing streaming Comet include the following:

Hidden iframe

A basic technique for dynamic web application is to use a hidden iframe HTML element (an <I>inline frame</I>, which allows a website to embed one HTML document inside another). This invisible iframe is sent as a chunked block, which implicitly declares it as infinitely long (sometimes called “forever frame”). As events occur, the iframe is gradually filled with script tags, containing JavaScript to be executed in the browser. Because browsers render HTML pages incrementally, each script tag is executed as it is received.[11]

One benefit of the iframe method is that it works in every common browser. Two downsides of this technique are the lack of a reliable error handling method, and the impossibility of tracking the state of the request calling process.[11]

XMLHttpRequest

The XMLHttpRequest (XHR) object, the main tool used by Ajax applications for browser–server communication, can also be pressed into service for server–browser Comet messaging, in a few different ways.

In 1995, Netscape Navigator added a feature called “server push”, which allowed servers to send new versions of an image or HTML page to that browser, as part of a multipart HTTP response (see History section, below), using the content type multipart/x-mixed-replace. Since 2004, Gecko-based browsers such as Firefox accept multipart responses to XHR, which can therefore be used as a streaming Comet transport.[12] On the server side, each message is encoded as a separate portion of the multipart response, and on the client, the callback function provided to the XHR onreadystatechange function will be called as each message arrives. This functionality is only included in Gecko-based browsers, though there is discussion of adding it to WebKit.[13]

Instead of creating a multipart response, and depending on the browser to transparently parse each event, it is also possible to generate a custom data format for an XHR response, and parse out each event using browser-side JavaScript, relying only on the browser firing the onreadystatechange callback each time it receives new data.

Ajax with long polling

None of the above streaming transports works across all modern browsers without negative side-effects. This forces Comet developers to implement several complex streaming transports, switching between them depending on the browser. Consequently many Comet applications use long polling, which is easier to implement on the browser side, and works, at minimum, in every browser that supports XHR. As the name suggests, long polling requires the client to poll the server for an event (or set of events). The browser makes an Ajax-style request to the server, which is kept open until the server has new data to send to the browser, which is sent to the browser in a complete response. The browser initiates a new long polling request in order to obtain subsequent events.

Specific technologies for accomplishing long-polling include the following:

XMLHttpRequest long polling

For the most part, XMLHttpRequest long polling works like any standard use of XHR. The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs.

Script tag long polling

While any Comet transport can be made to work across subdomains, none of the above transports can be used across different second-level domains (SLDs), due to browser security policies designed to prevent cross-site scripting attacks.[14] That is, if the main web page is served from one SLD, and the Comet server is located at another SLD, Comet events cannot be used to modify the HTML and DOM of the main page, using those transports. This problem can be side-stepped by creating a proxy server in front of one or both sources, making them appear to originate from the same domain. However, this is often undesirable for complexity or performance reasons.

Unlike iframes or XMLHttpRequest objects, script tags can be pointed at any URI, and JavaScript code in the response will be executed in the current HTML document. This creates a potential security risk for both servers involved, though the risk to the data provider (in our case, the Comet server) can be avoided using JSONP.

A long-polling Comet transport can be created by dynamically creating script elements, and setting their source to the location of the Comet server, which then sends back JavaScript (or JSONP) with some event as its payload. Each time the script request is completed, the browser opens a new one, just as in the XHR long polling case. This method has the advantage of being cross-browser while still allowing cross-domain implementations.[14]

referrer : http://en.wikipedia.org/wiki/Comet_%28programming%29

<script type="text/javascript">

 

    $(document).ready(function () {

 

        var ctr = 1;

        $.PeriodicalUpdater('@Url.Content("~/SupportService/MessageQueue")', {

            minTimeout: 10 * 1000,

            maxTimeout: 10 * 60 * 1000,

            multiplier: 2.3,

            type: 'json',

            data: function () { return ctr++; },

            cache: true

        }, function (data) {

            $('#curtime').html(data.curtime);

        });

 

    });

 

</script>

jsfile : https://github.com/RobertFischer/JQuery-PeriodicalUpdater/

demo   : http://demo.smokejumperit.com/demo.html

RobertFischer / JQuery-PeriodicalUpdater

A port of Prototype's Ajax.PeriodicalUpdater function to jQuery.

Basically, this function polls some remote service at fairly regular internvals, and (optionally) processes the result via a callback. The period of calls will decay as long as the same response keeps coming back from the server (either in the form of repeated data or in the form of a 304 Not Modified status), which reduces the load on the server naturally. The first Ajax call happens as a page 'onReady' handler (ie: the jQuery(function) call), so it is safe to put the PeriodicalUpdater call anywhere on the page.

Usage: $.PeriodicalUpdater('/path/to/service', { method: 'get', // method; get or post data: '', // array of values to be passed to the page - e.g. {name: "John", greeting: "hello"} minTimeout: 1000, // starting value for the timeout in milliseconds maxTimeout: 8000, // maximum length of time between requests multiplier: 2, // the amount to expand the timeout by if the response hasn't changed (up to maxTimeout) type: 'text', // response type - text, xml, json, etc. See $.ajax config options maxCalls: 0, // maximum number of calls. 0 = no limit. autoStop: 0 // automatically stop requests after this many returns of the same data. 0 = disabled. }, function(remoteData, success, xhr, handle) { // Process the new data (only called when there was a change) });

The "data" value can be one of three things:

  • A scalar, in which case it will be used constantly.
  • A JSON map/object, in which case it will be turned into key/value pairs by jQuery
  • An anonymous function, in which case it will be executed before each AJAX call. See jQuery.ajax for more information.

Any of the other standard $.ajax configuration options can be passed to the setting map.
The only exception is the flag that treats modifications as errors. That’s always going to be 'true'.

The function call returns a handle. You can call .stop() on this handle in order to stop the updating and ignore any subsequent responses. If the maximum number of calls, .stop(), or the autoStop has been triggered, you can restart the updater using .restart() on the handle. This handle is also passed into the callback function as the fourth argument.

More info, including advantages over 360innovate version, see the blog post on EnfranchisedMind.

referrer: https://github.com/RobertFischer/JQuery-PeriodicalUpdater/blob/master/README.md

 

Hiç yorum yok:

Yorum Gönder