Detailed XMLHttpRequest (ii) Response attributes, binary data, monitoring upload download Progress _javascript skills

Source: Internet
Author: User

Analyze and manipulate Responsexml properties

If you use XMLHttpRequest to get the content of a remote XML document, the Responsexml attribute will be a DOM object parsed by an XML document, which is difficult to manipulate and analyze. Here are five main ways to parse XML documents:
1. Use XPath to navigate to the elaboration section of the document.
2. Convert it into a JavaScript object tree using Jxon.
3. Manual parsing and serialization of XML as a string or object.
4. Use XMLSerializer to serialize a DOM tree into a string or file.
5. If you know the contents of an XML document in advance, you can use REGEXP. If you are affected by a newline character when using a REGEXP scan, you may want to remove all line breaks. However, this approach is a "last resort" because the method may fail if the XML code changes slightly.

Parsing and manipulating ResponseText properties that contain HTML documents

Note: in the XMLHttpRequest specification, HTML is allowed to parse through the Xmlhttprequest.responsexml attribute. Please read the HTML in XMLHttpRequest for more details.
If you use XMLHttpRequest to get an HTML page from a remote location, all HTML tags are stored as strings in the ResponseText attribute, making it difficult to manipulate and parse the tags. There are three main ways to parse these HTML tags:
1. Use the Xmlhttprequest.responsexml property.
2. Inject content through Fragment.body.innerHTML into a document fragment and traverse the fragments in the DOM.
3. If you know the content of the HTML document in advance, you can use REGEXP. If you are affected by a newline character when using a REGEXP scan, you may want to remove all line breaks. However, this approach is a "last resort" because the method may fail if the HTML code changes slightly.

Handling binary Data

Although XMLHttpRequest is generally used to send and receive text data, it can actually send and receive binary content. There are many well tested ways to force the use of XMLHttpRequest to send binary data. Using the XMLHttpRequest. Overridemimetype () method is a solution, although it is not a standard method.

 var oreq = new XMLHttpRequest ();
Oreq.open ("Get", url, true);
Retrieve data unprocessed as a binary string
oreq.overridemimetype ("Text/plain; Charset=x-user-defined ");

New Responsetype attributes are added to the XMLHttpRequest Level 2 specification, making it easier to send and receive binary data.

 var oreq = new XMLHttpRequest ();
Oreq.onload = function (e) {
 var arraybuffer = xhr.response;//Not ResponseText/
 * ... */
}
oreq.open ("G ET ", url, true);
Oreq.responsetype = "Arraybuffer";
Oreq.send (); 

using a JavaScript type array to accept binary data

You can change the data type of a response returned from the server by setting the Responsetype property of a XMLHttpRequest object. The available property values are an empty string (default), "Arraybuffer", "blob", "Document", and " Text ". The value of the response property differs depending on the value of the Responsetype property and may be a arraybuffer, Blob, Document, String, or null (if the request is not completed or fails)
The following example reads a binary image file and creates an array of 8-bit unsigned integers by the binary native byte of the file.

 var oreq = new XMLHttpRequest ();
Oreq.open ("Get", "/myfile.png", true);
Oreq.responsetype = "Arraybuffer";
Oreq.onload = function (oevent) {
 var arraybuffer = oreq.response;//Note: not Oreq.responsetext
 if (arraybuffer) {
   var ByteArray = new Uint8array (arraybuffer);
  for (var i = 0; i < bytearray.bytelength; i++) {
   //Every byte in the array to operate
  }}
 }
;
Oreq.send (NULL); 

In addition to the above method, you can also use the Blobbuilder API to add Arraybuffer data directly into a BLOB object, and because the API is still in the experimental phase, you need to add a specific prefix:

 var blobbuilder = window. Mozblobbuilder | | Window. Webkitblobbuilder | | Window. Msblobbuilder | | Window. Blobbuilder;
var oreq = new XMLHttpRequest ();
Oreq.open ("Get", "/myfile.png", true);
Oreq.responsetype = "Arraybuffer";
Oreq.onload = function (oevent) {
 var blobbuilder = new Blobbuilder ();
 Blobbuilder.append (oreq.response);
 var blob = Blobbuilder.getblob ("Image/png");
 // ...
};
Oreq.send (); 

Accept binary data in old browsers
the following Load_binary_resource () method loads the binary data from the specified URL and returns the data to the caller.

 function Load_binary_resource (URL) {
 var req = new XMLHttpRequest ();
 Req.open (\ ' get\ ', url, false);
 XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
 req.overridemimetype (\ ' Text/plain; Charset=x-user-defined\ ');
 Req.send (null);
 if (req.status!=) return \ ' \ ';
 return req.responsetext;
} 

The most amazing operation on line fifth, the line overrides the default MIME type, forcing the browser to treat the response as a plain text file, using a user-defined character set. This is to tell the browser, do not parse the data, directly returned to the unhandled bytecode.

 var filestream = Load_binary_resource (URL);
var abyte = filestream.charcodeat (x) & 0xFF; High-order bytes thrown away (F7) 

The previous example gets the byte offset at x from the requested binary data. The valid offset range is 0 to filestream.length-1.
View download files using the XMLHttpRequest download file for more information.

Send binary Data

The Send method of the XMLHttpRequest object has been enhanced to send binary data by simply passing in a arraybuffer, Blob, or File object.
The following example creates a text file and uses the Post method to send the file to the server. You can also use other binary data types other than text files.

 var oreq = new XMLHttpRequest ();
Oreq.open ("POST", url, true);
Oreq.onload = function (oevent) {
 //upload completed.
};
var bb = new Blobbuilder (); The appropriate prefix is required: window. Mozblobbuilder or window. Webkitblobbuilder
bb.append (\ ' abc123\ ');
Oreq.send (Bb.getblob (\ ' text/plain\ ')); 

To send an array of types as binary data
You can send the JavaScript type array as binary data.

 var myarray = new Arraybuffer (in);
var longint8view = new Uint8array (myarray);
for (var i=0; i< longint8view.length; i++) {
 longint8view[i] = i% 255;
}
var xhr = new XMLHttpRequest;
Xhr.open ("POST", url, false);
Xhr.send (myarray); 

The example above creates a 512-byte 8-bit integer array and sends it, of course, you can also send arbitrary binary data

Monitoring progress
Supports DOM-progress event monitoring for XMLHttpRequest transmissions, following the Web API Progress Event Specification: These events implement the Progressevent interface.

 var req = new XMLHttpRequest ();
Upload listening
Req.addeventlistener ("Progress", updateprogress, false);
Req.addeventlistener ("Load", Transfercomplete, false);
Req.addeventlistener ("Error", transferfailed, false);
Req.addeventlistener ("Abort", transfercanceled, false);

Req.open (...);
...
Progress on transfers from the server to the client (downloads)
function updateprogress (evt) {
 if (evt.lengthc omputable) {
  var percentcomplete = evt.loaded/evt.total;
  ...
 } else {
  //Unable to compute progress information since the total size is unknown
 }
} 

Note: You need to add event sniffing before requesting the call to open (). Otherwise the progress event will not be triggered.
In the previous example, the progress event was specified by the UpdateProgress () function and received the total number of bytes transmitted and the number of bytes transmitted loaded, the overall length of the data transmitted from the "Content-length" header ( bytes). However, if the value of the Lengthcomputable property is False, then the total number of bytes is unknown and the sum value is 0, and the Lengthcomputable property is true if the length is known
The progress event also exists in both the download and upload transmissions. Download-related events are triggered on the XMLHttpRequest object, just like the example above. Uploading related events is triggered on the Xmlhttprequest.upload object, as follows:

 var req = new XMLHttpRequest ();
Download listening
Req.upload.addEventListener ("Progress", updateprogress);
Req.upload.addEventListener ("Load", transfercomplete);
Req.upload.addEventListener ("error", transferfailed);
Req.upload.addEventListener ("Abort", transfercanceled);
Req.open (); 

Note: The progress event is not valid when using the file: protocol.
Use the Loadend event to detect all three load completion conditions (abort, load, error):
Req.addeventlistener ("Loadend", Loadend, false);
It should be noted that there is no way to know exactly what condition the Loadend event receives from the termination of the operation, but you can use this event at the end of all transmissions.

The XMLHttpRequest object triggers different types of events at different stages of the request, so it does not need to check the ReadyState property.
When send () is invoked, a single Loadstart event is triggered. When the server's response is loading, the XMLHttpRequest object progress events, usually around 50 milliseconds, so you can use these events to give users feedback on the progress of the request.
If the request completes quickly, it may never trigger the progress event. When the event completes, the Load event is triggered.
HTTP requests cannot be completed in 3 cases, corresponding to 3 kinds of events. If the request times out, the timeout event is triggered. If the request is aborted, the abort event is triggered. A network error such as too much redirection prevents the request from completing, but the error event is triggered when these occur.
For any specific request, the browser will only trigger one of the load, abort, timeout, and error events, as well as the progress event.

 if (\ ' Onprogress\ ' in (New XMLHttpRequest ())} {//Detect support for Progress event
  var request = new XMLHttpRequest ();
  request.onprogress = function (e) {
    if (e.lengthcomputable) {
      progress.innerhtml = Math.Round (100* e.loaded/ e.total) + \ '%\ ';}}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.