High-performance AJAX

Source: Internet
Author: User
Tags browser cache

Five common ways to request data1, XMLHttpRequest (XHR) var url = '/data.php '; var params = [' id=934875 ', ' limit=20 '];var req = new XMLHttpRequest (); r Eq.onreadystatechange = function () { if (req.readystate = = = 3) {//Receive only partial datavar datasofar = Req.responsetext;
...
   }    if (req.readystate = = = 4) {        var responseheaders = Req.getallrespon Seheaders ();                //Get The response  headers.        var d ATA = Req.responsetext;                          ,         &NB Sp          //Get the data.                    &N Bsp                          ,         &NB Sp                                  // Process the Data here...     }}req.open (' GET ', url + '? ' + params.join (' & '), true); Req.setrequestheade R (' X-requested-with ', ' XMLHttpRequest ');          //Set a request &nbsP;header.req.send (NULL);                          ,         &NB Sp                          ,         &NB Sp Send the request.Note: For those that do not modify the server state just take back the data, you should use Get mode, get is cached and can improve performance if multiple fetch to the same datapost should be URL length close to or more than 2048 when the time, because IE limit the length of the URL, more than will be cut offMaximum limit: Cannot request data across domains2. Dynamically generate Insert Script tag var scriptelement = document.createelement (' script '); scriptelement.src = ' http://any-domain.com/ Javascript/lib.js ';d ocument.getelementsbytagname (' head ') [0].appendchild (scriptelement); function Jsoncallback (    jsonstring) {var data = eval (' (' + jsonstring + ') ');     Process the data Here ...} Lib.js:jsonCallback ({"Status": 1, "Colors": ["#fff", "#000", "#ff0000"]});Note: This approach breaks through the above XHR not allow cross-domain restrictions, but loses a lot of controllability: the header and the request cannot be sent together. You can only request a Get method to use post. You cannot set a timeout or retry a request, even if you do not know that the request failed. You need to wait until all the data is received before you can access processing. Unable to access the header of the response or the entire response as a string. The most important thing is that the response is executed as a script tag, so it has to be a direct executable JavaScript code. 3, multipart XHR client: var req = new XMLHttpRequest ();
Req.open (' GET ', ' rollup_images.php ', true);
Req.onreadystatechange = function () {
if (req.readystate = = 4) {
Splitimages (Req.responsetext);
}
};req.send (NULL); function Splitimages (imagestring) {//For processing the returned long string picture data var imageData = Imagestring.spli    T ("\u0001");    var imageelement;        for (var i = 0, len = imagedata.length; i < Len; i++) {imageelement = document.createelement (' img ');        IMAGEELEMENT.SRC = ' data:image/jpeg;base64, ' + imagedata[i];    document.getElementById (' container '). appendchild (imageelement);                        }} server (PHP): $images = Array (' kitten.jpg ', ' sunset.jpg ', ' baby.jpg '); Read the images and convert them into base64 encoded strings.
foreach ($images as $image) {
$image _fh = fopen ($image, ' R ');
$image _data = fread ($image _fh, FileSize ($image)); Fclose ($image _fh);
$payloads [] = Base64_encode ($image _data);
}
} $newline = Chr (1);                            This character won ' t appear naturally in any base64 String.echo implode ($newline, $payloads); Roll up those strings into one long string and output it.    Used to restore a string to a function that the browser can recognize: function Handleimagedata (data, mimeType) {var img = document.createelement (' img ');    IMG.SRC = ' data: ' + MimeType + '; base64, ' + data; return img;}    function Handlecss (data) {var style = document.createelement (' style ');    Style.type = ' text/css ';    var node = document.createtextnode (data); Style.appendchild (node);
document.getElementsByTagName (' head ') [0].appendchild (style);
}function Handlejavascript (data) {
eval (data);
}  If there are too many data, such as 200 images, you cannot wait until the entire string is processed, and you should dispose of the received resources: var req = new XMLHttpRequest (); var getlatestpacketinterval, Lastlength = 0;req.open (' GET ', ' rollup_images.php ', true); req.onreadystatechange = Readystatehandler;req.send (null); function Readystatehandler {    if (req.readystate = = = 3 && Getlatestpacketinterval = = null) {  &N Bsp     Getlatestpacketinterval = Window.setinterval (function () {              & nbsp                 //Start polling.            GE Tlatestpacket ();       },;   }    if (req.readystate = = 4) {    & nbsp   Clearinterval (Getlatestpacketinterval);                          ,         &NB Sp                 //Stop polling.    &NBsp   Getlatestpacket ();                          ,         &NB Sp                          ,         &NB Sp      //Get The last packet.   }}function Getlatestpacket () {        & nbsp                          ,         &NB Sp              //execute the function once every 15 milliseconds, then take the new data of the response and wait until a resource delimiter appears to dispose of this resource     var length = req.responsetext.length;    var packet = req.responseText.substring (lastlength, length);    Processpacket (packet);    lastlength = length;}Note: This is the latest technology that allows multiple resources to be sent from the server to the client with only one HTTP request. Package the resources (either CSS files, HTML fragment,javascript code, or base64 images) into a long string, which is differentiated by the mine-type of each resource as JavaScript handles the long string. Disadvantage: The resources are not cached in the browser, because the resources are sent through the form of a string to the browser, there is no way to put the file through the program in the browser cache. IE6, 7 not supportedReadyState3 or Data:urls. Pros: Reduce HTTP requests and speed up4, IFRAMES5, comet first three kinds of high performance, first choice send data to server mode:1, XMLHttpRequest (XHR)      function xhrpost (URL, params, callback) {    var req = new Xmlhttpreq Uest ();    req.onerror = function () {        setTimeout (function () {      &NB Sp    xhrpost (URL, params, callback);       }, +);   };    Req.onready StateChange = function () {        if (req.readystate = = 4) {            if (callback && typeof callback = = = ' function ') {                callback ( );           }       }   };    req.open (' POST ', u RL, True);    req.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');    Req.setrequestheader (' Content-length ', params.length);    req.send (Params.join (' & '));}Note: Although it is often used to request data from the server, it can also be used to send data to the server. When you want to send data back to the server beyond the URL limit, using post to return it is very useful 2, Beaconsvar url = '/status_tracker.php '; var params = [' step=2 ', ' time=1248027314 '];(new Image ()). src = url + '? ' + Params.join (' & ');    Beacon.onload = function () {if (this.width = = 1) {//Success.    } else if (this.width = = 2) {//Failure; create another beacon and try again. }};beacon.onerror = function () {//Error; Wait a bit, then create another beacon and try again.
};Note: The src URL points to the PHP script that is processed on the server. Disadvantage: Cannot use post, can only pass through get, so the data length is limited. The response returned is very limited. Advantages: Fastest and most efficient

High-performance AJAX

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.