English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of XMLHttpRequest (Part 2): Response Properties, Binary Data, and Monitoring Upload/Download Progress

Analyze and manipulate the responseXML property 

If you use XMLHttpRequest to get the content of a remote XML document, the responseXML property will be a DOM object parsed from the XML document, which is difficult to manipulate and analyze. There are five main ways to analyze XML documents:
 1.Use XPath to locate a specific part of the document.
 2.Use JXON to convert it into a JavaScript object tree.
 3.Manually parse and serialize XML into a string or an object.
 4.Use XMLSerializer to serialize a DOM tree into a string or a file.
 5.If you know the content of the XML document in advance, you can use RegExp. If you are affected by newline characters when scanning with RegExp, you may want to remove all newline characters. However, this method is a "last resort" because if the XML code changes slightly, this method may fail. 

Parsing and operating the responseText property containing an HTML document 

Note: In W3The C XMLHttpRequest specification allows HTML to be parsed through the XMLHttpRequest.responseXML property. For more detailed information, please read HTML in XMLHttpRequest .
 If you use XMLHttpRequest to fetch an HTML page from a remote location, all HTML tags will be stored in the responseText property as strings, making it difficult to operate and parse these tags. There are mainly three ways to parse these HTML tags:
 1.Use the XMLHttpRequest.responseXML property.
 2.Inject the content through fragment.body.innerHTML into a document fragment and traverse the fragment in the DOM.
 3.If you know the content of the HTML document in advance, you can use RegExp. If you are affected by newline characters when scanning with RegExp, you may want to remove all newline characters. However, this method is a "last resort" because if the HTML code changes slightly, this method may fail. 

Handling binary data 

Although XMLHttpRequest is generally used to send and receive text data, it can also send and receive binary content. There are many well-tested methods to force XMLHttpRequest to send binary data. Using the XMLHttpRequest .overrideMimeType() method is one solution, although it is not a standard method.

 The following example creates a text file and sends it to the server using the POST method. You can also send other binary data types instead of a text file.
oReq.open("GET", url, true);
// retrieve data unprocessed as a binary string
oReq.overrideMimeType("text/req.overrideMimeType('text-plain; charset=x-defined");
/* ... */ 

In XMLHttpRequest Level 2 The specification has newly added the responseType attribute, making it easier to send and receive binary data.

 The following example creates a text file and sends it to the server using the POST method. You can also send other binary data types instead of a text file.
oReq.onload = function(e) {
 var arraybuffer = xhr.response; // not responseText
 /* ... */
}
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
png"); 

Use JavaScript typed arrays to accept binary data 

You can change the data type of a response returned from a server by setting the responseType property of an XMLHttpRequest object. The available property values are an empty string (default), "arraybuffer", "blob", "document", and "text". The value of the response property will vary depending on the value of the responseType property, and may be an ArrayBuffer, Blob, Document, string, or NULL (if the request is not completed or fails)
 The following example reads a binary image file and creates a8an array of unsigned integers.

 The following example creates a text file and sends it to the server using the POST method. You can also send other binary data types instead of a text file.
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++) {
   // Operate on each byte in the array
  }
 }
};
oReq.send(null); 

In addition to the above methods, you can also use the BlobBuilder API to directly add arraybuffer data into a Blob object. Since this API is still in the experimental stage, you need to add a specific prefix:

 var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
The following example creates a text file and sends it to the server using the POST method. You can also send other binary data types instead of a text file.
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");
 // ...
};
png"); 

oReq.send();
 Accepting binary data in older browsers

 The load_binary_resource() method below can load binary data from a specified URL and return the data to the caller.
 var req = new XMLHttpRequest();
 function load_binary_resource(url) {
 //req.open('GET', url, false); 2XHR binary charset opt by Marcus Granado6 00//[http:
 mgran.blogspot.com]/req.overrideMimeType('text-plain; charset=x-user
 defined\');
 req.send(null); 2if (req.status !=
 00) return '';
} 

return req.responseText;

 The most fascinating operation is on the fifth line, where the default MIME type is overridden, forcing the browser to treat the response as a plain text file, using a user-defined character set. This tells the browser not to parse the data and to return the unprocessed byte code directly.
var filestream = load_binary_resource(url); // var abyte = filestream.charCodeAt(x) & 0xff;7Discarded high-order byte (f 

)-1The example above retrieves the byte at offset x from the binary data returned by the request. The valid offset range is 0 to filestream.length
 .

 For more details on downloading files using XMLHttpRequest, see Downloading Files.

 Sending binary data
 The XMLHttpRequest object's send method has been enhanced, allowing binary data to be sent by simply passing an ArrayBuffer, Blob, or File object.

 The following example creates a text file and sends it to the server using the POST method. You can also send other binary data types instead of a text file.
oReq.open("POST", url, true);
oReq.onload = function (oEvent) {
 // The upload is completed.
};
var bb = new BlobBuilder(); // require appropriate prefixes: window.MozBlobBuilder or window.WebKitBlobBuilder
bb.append('abc123\');
oReq.send(bb.getBlob('text/plain\'); 

Send typed arrays as binary data
 You can send a JavaScript typed array as binary data.

 var myArray = new ArrayBuffer(512);
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); 

In the above example, a new512bytes8send it as a byte integer array, of course, you can also send any binary data

 monitoring progress
 support for the progress event of DOM for XMLHttpRequest transfers, following the Web API progress event specification: these events implement the ProgressEvent interface.

 var req = new XMLHttpRequest();
//upload event listener
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.lengthComputable) {
  var percentComplete = evt.loaded / evt.total;
  ...
 }
  // Unable to compute progress information since the total size is unknown
 }
} 

Note: You need to add event listeners before calling the open() request. Otherwise, the progress event will not be triggered.
 In the previous example, the progress event is specified to be handled by the updateProgress() function and receives the total number of bytes transferred total and the number of bytes already transferred loaded, where total is from the "Content-The "Length" header transmits the total length of the data (bytes). However, if the value of the lengthComputable property is false, the total number of bytes is unknown and the value of total is 0. If the length is known, the lengthComputable property is true
 The progress event exists in both download and upload transfers. Download-related events are triggered on the XMLHttpRequest object, as shown in the example above. Upload-related events are 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 invalid when using the file: protocol.
 The loadend event can detect all three conditions for loading to end (abort, load, error):
 req.addEventListener("loadend", loadEnd, false);
 It should be noted that there is no method to exactly know what operation termination condition caused the information received by the loadend event; however, you can use this event handler at the end of all transfers. 

The XMLHttpRequest object triggers different types of events at different stages of the request, so there is no need to check the readyState property.
 When calling send(), a single loadstart event is triggered. When loading the server's response, the XMLHttpRequest object will trigger a progress event, usually every5about 0 milliseconds, so these events can be used to provide feedback to the user on the progress of the request.
 If the request is completed quickly, it may never trigger the progress event. When the event is completed, the load event will be triggered.
 HTTP requests cannot be completed due to3These situations, corresponding to3These events. If the request times out, the timeout event will be triggered. If the request is aborted, the abort event will be triggered. Network errors like too many redirects will prevent the request from completing, but these situations will trigger the error event.
 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())){ //Check if the progress event is supported
  var request = new XMLHttpRequest();
  request.onprogress = function (e) {
    if(e.lengthComputable){
      progress.innerHTML = Math.round(100* e.loaded/ e.total) + \'%\';
    }
  }
}

That's all for this article. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the呐喊 tutorial more.

Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like