Five techniques for requesting data from servers

Source: Internet
Author: User

Ajax, at its most basic level, is a method of communicating with the server without reloading the current page. data can be obtained from the server or sent to the server. There are multiple methods to construct this communication channel, each of which has its own advantages and limitations.
There are five common technologies used to request data from the server:
(1) XMLHttpRequest (xhr)
(2) Insert dynamic script labels
(3) Framework
(4) comet
(5) xhr
Three techniques used in modern high-performance JavaScript are xhr, dynamic script tag insertion, and multi-part xhr. The use of comet and IFRAME (as data transmission technology) is often the limit, which is not discussed here.

  I. XMLHttpRequest
Currently, XMLHttpRequest (xhr) is used to send and receive data asynchronously. All modern browsers support it well and precisely control sending requests and data reception. You can add arbitrary header information and parameters (including get and post) to the request message, read the header information returned from the server, and the response text itself. The following is an example:
VaR url = '/data. php ';
VaR Params = [
'Id = 934875 ',
'Limit = 20'
];
VaR Req = new XMLHttpRequest ();
Req. onreadystatechange = function (){
If (req. readystate === 4 ){
VaR responseheaders = Req. getAllResponseHeaders ();
VaR DATA = Req. responsetext;
}
}
Req. Open ('get', URL + '? '+ Params. Join (' & '), true );
Req. setRequestHeader ('x-requested-with', 'xmlhttprequest ');
Req. Send (null );
This example shows how to request data from a URL, use parameters, and read Response Message and header information. The value of readystate 4 indicates that the entire response packet has been received and can be used for operations.
If the value of readystate is 3, the system is interacting with the server, and the response message is still being transmitted. This is the so-called "stream", which is a powerful tool to improve the performance of data requests:
Req. onreadystatechange = function (){
If (req. readystate = 3 ){
VaR datasofar = Req. responsetext;
...
}
Else if (req. readystate === 4 ){
VaR DATA = Req. responsetext;
...
}
}
Because xhr provides advanced control, the browser adds some restrictions on it. You cannot use xhr to run from the current Code Data is requested outside the domain, and the old version of IE does not provide readystate3, which does not support stream. The data returned from a request is treated as a string or an XML object, which means processing a large amount of data will be quite slow.
Despite these shortcomings, xhr is still the most common and powerful request data technology and should be your first choice.
When xhr is used to request data, you can select post or get. If the request does not change the server status but only retrieves data (also known as idempotent actions), use get. GET requests are buffered. If you extract the same data multiple times, you can improve the performance.
Use post to extract data only when the URL and parameter length exceed 2 '048 characters. Because Internet Explorer limits the URL Length and is too long, the request (parameter) is truncated.
  Ii. Insert dynamic script labels
This technology overcomes xhr's maximum limit: it can obtain data from servers in different domains. This is a hacker technique, instead of instantiating a special object. You create a new script tag using JavaScript and set its source attribute to a URL pointing to different domains.
VaR scriptelement = Document. createelement ('script ');
Scriptelement. src = 'HTTP: // any-domain.com/javascript/lib.js ';
Document. getelementsbytagname_r ('head') [0]. appendchild (scriptelement );
However, dynamic script label insertion only provides less control than xhr. You cannot send an information header Through the request. Parameters can only be passed through the get method, but not post. You cannot set request timeout or retry. In fact, you do not need to know whether the request has failed. You must wait until all data is returned before accessing them. You cannot access the response header or access the entire response message as the access string.
The last point is very important. Because the response packet is used as the source code of the script tag, it must be executable JavaScript. You cannot use bare XML or bare JSON. Any data, regardless of the format, must be assembled in a callback function.
VaR scriptelement = Document. createelement ('script ');
Scriptelement. src = 'HTTP: // any-domain.com/javascript/lib.js ';
Document. getelementsbytagname_r ('head') [0]. appendchild (scriptelement );
Function jsoncallback (jsonstring ){
VaR DATA = ('+ jsonstring + ')');
}
In this example, the Lib. js file calls the jsoncallback function to assemble data:
Jsoncallback ({"status": 1, "Colors": ["# fff", "#000", "# ff0000"]});
Despite these limitations, this technology is still very fast. The response result is to run javascript instead of being processed as a string. Because of this, it may be the fastest way to obtain and parse data on the client. We compared the performance of dynamic script label insertion and xhr, which is later in the JSON section.
Please be careful when using this technology to request data from servers that you cannot directly control. Javascript has no permissions or access control, so any code inserted using dynamic SCRIPT tags on your page can fully control the entire page. This includes modifying any content, redirecting users to another site, or tracking their operations on the page and sending data to a third party. Be careful when using code from external sources.
  Iii. Multiple xhr
Multiple xhr (mxhr) allows you to retrieve multiple resources from the server with only one HTTP request. It packs resources (which can be CSS files, HTML fragments, JavaScript code, or base64 encoded images) into a large string defined by a specific separator and sends it to the client from the server side. JavaScript code processes this long string and parses each resource based on its media type and other "Information headers.
Let's follow this process from start to end. First, send a request to request several image resources from the server:
VaR Req = new XMLHttpRequest ();
Req. Open ('get', 'rollup _ images. php', true );
Req. onreadystatechange = function (){
If (req. readystate = 4 ){
Splitimages (req. responsetext );
}
};
Req. Send (null );
This is a very simple request. You request data from rollup_images.php. Once you receive the returned result, you can submit it to the splitimages function for processing.
Next, the server reads the images and converts them to strings:
$ Images = array('kitten.jpg ', 'sunset.jpg', 'baby.jpg ');
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 );
Echo implode ($ newline, $ payloads );
This PHP Code reads three images and converts them into base64 strings. They are connected with a simple character, Unicode 1, and then returned to the client.
Then return to the client. The data is processed by the splitimage function:
Function splitimages (imagestring ){
VaR imagedata = imagestring. Split ("\ 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 );
}
}
This function splits the concatenated string into three segments. Each segment is used to create an image element and insert it into the page. The image is not converted from base64 to binary, but uses data: URL and specifies the image/JPEG media type.
The final result is: three images are passed into the browser in an HTTP request. You can also input 20 or 100 messages. The response packet is larger, but it is only an HTTP request. It can also be extended to other types of resources. JavaScript files, CSS files, HTML fragments, and many types of images can be merged into one response. Any data type can be sent as a string processed by JavaScript. The following functions are used to convert JavaScript code, CSS style sheets, and images into available resources of the browser:
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_r ('head') [0]. appendchild (style );
}
Function handlejavascript (data ){
(Data );
}
As mxhr response packets become larger and larger, it is necessary to process each resource immediately when it is received, rather than waiting for the entire response message to be received. This can be achieved by listening to readystate3:
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 ){
Getlatestpacketinterval = Window. setinterval (function (){
Getlatestpacket ();
}, 15 );
}
If (req. readystate === 4 ){
Clearinterval (getlatestpacketinterval );
Getlatestpacket ();
}
}
Function getlatestpacket (){
VaR length = Req. responsetext. length;
VaR packet = Req. responsetext. substring (lastlength, length );
Processpacket (packet );
Lastlength = length;
}
When readystate3 is triggered for the first time, a timer is started. Check the new data in the Response Message every 15 milliseconds. Data fragments are collected until a separator is found, and everything is processed as a complete resource. The code for using mxhr in a robust way is complex but worth further research.
This technology has some disadvantages. The biggest drawback is that the resources obtained in this method cannot be cached by the browser. If you use mxhr to obtain a specific CSS file and load it normally on the next page, it is not in the cache. Because the whole batch of resources are transmitted as a long string and then separated by JavaScript code. Unable to use Program Put files in the browser cache, so resources obtained using this method cannot be stored there.
Another drawback is that Internet Explorer in earlier versions does not support readystate3 or data: URL. Both Internet Explorer 8 are supported, but you must try to make changes in Internet Explorer 6 and 7.
Despite these disadvantages, mxhr still significantly improves the overall page performance in some cases: webpages contain resources that are not used elsewhere (so they do not need to be cached), especially images.
Websites use unique packaged JavaScript or CSS files for each page to reduce HTTP requests, because they are unique for each page, so they do not need to be read from the cache, unless a specific page is reloaded.
As HTTP requests are one of the most challenging bottlenecks in Ajax, reducing the number of requests has a great impact on the performance of the entire page. This is especially true when you convert 100 image requests to an mxhr request. Ad hoc tests a large number of images on modern browsers. The results show that this technology is 4 to 10 times faster than one request.
Sometimes you don't care about receiving data, but you just need to send the data to the server. You can send non-private information of users for future analysis, capture all script errors, and send the relevant details to the server for record and prompt. When data only needs to be sent to the server, there are two widely used technologies: xhr and lamps.
  (1) XMLHttpRequest
Although xhr is mainly used to obtain data from the server, it can also be used to send data back. Data can be sent back in get or post mode, as well as any number of HTTP information headers. This gives you great flexibility. Xhr is particularly useful when the amount of data you send back to the server exceeds the maximum URL Length of the browser. In this case, you can use the POST method to send back data:
VaR url = '/data. php ';
VaR Params = [
'Id = 934875 ',
'Limit = 20'
];
VaR Req = new XMLHttpRequest ();
Req. onerror = function (){
// Error.
};
Req. onreadystatechange = function (){
If (req. readystate = 4 ){
// Success.
}
};
Req. Open ('post', URL, true );
Req. setRequestHeader ('content-type', 'application/X-WWW-form-urlencoded ');
Req. setRequestHeader ('content-length', Params. Length );
Req. Send (Params. Join ('&'));
As you can see in this example, if we fail, we will not do anything. When xhr is used to capture Login User statistics, this is usually okay. However, if the data sent to the server is crucial, you can add the code and try again when it fails:
Function xhrpost (URL, Params, callback ){
VaR Req = new XMLHttpRequest ();
Req. onerror = function (){
SetTimeout (function (){
Xhrpost (URL, Params, callback );
},1000 );
};
Req. onreadystatechange = function (){
If (req. readystate = 4 ){
If (callback & typeof callback === 'function '){
Callback ();
}
}
};
Req. Open ('post', URL, true );
Req. setRequestHeader ('content-type', 'application/X-WWW-form-urlencoded ');
Req. setRequestHeader ('content-length', Params. Length );
Req. Send (Params. Join ('&'));
}
When xhr is used to send data back to the server, it is faster than get. This is because for a small amount of data, sending a GET request to the server takes up a separate packet. On the other hand, a post sends at least two data packets, one for the Information header. The other is used for the post body. Post is more suitable for sending a large amount of data to the server, that is, because it does not care about the number of extra packets, and because of the URL length restrictions of Internet Explorer, it cannot use too long GET requests.
  (2) lamps
This technique is very similar to inserting dynamic script labels. Javascript is used to create a new image object and set SRC to the URL of a script file on the server. This URL contains the key-value pair data that we intend to return in get format. Note that the IMG elements are not created or inserted into the Dom.
VaR url = '/status_tracker.php ';
VaR Params = [
'Step = 2 ',
'Time = 100'
];
(New image (). src = URL + '? '+ Params. Join ('&');
The server retrieves and saves the data without returning anything to the client. Therefore, no actual image is displayed. This is the most effective way to send information back to the server. The cost is small, and any server errors do not affect the client.
Simple image lamps mean you are limited to what you can do. You cannot send post data, so you are limited by the URL length to a fairly small number of characters. You can use very limited methods to receive returned data. You can listen to the load event of the image object, which tells you whether the server has successfully received the data. You can also check the width and height of the image returned by the server (if an image is returned) and use these numbers to notify your server of the status. For example, if the width is 1, it indicates "successful", and 2 indicates "retry ".
If you do not need to return data for the response, you should send a 204 NO content response code without the message body. It will prevent the client from waiting for the message body that will never arrive:
VaR url = '/status_tracker.php ';
VaR Params = [
'Step = 2 ',
'Time = 100'
];
VaR beacon = new image ();
Beacon. 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.
};
The lamp is the fastest and most effective way to send data back to the server. The server does not need to send back any response body at all, so you do not have to worry about downloading data from the client. The only drawback is that the received response type is limited. If you need to return a large amount of data to the client, use xhr. If you only care about sending data to the server (which may require a few replies), use the image lamp.

OriginalArticle, Reprinted, please note:   Reprinted from http://www.yiiyaa.net/

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.