Analyze and manipulate responseXML attributes
If you use XMLHttpRequest to obtain the contents 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. Here are five main ways to analyze XML documents:
1. Use XPath to locate the formulation part of the document.
2. Use JXON to convert it into a JavaScript object tree.
3. Manually parse and serialize XML into strings or objects.
4. Use XMLSerializer to serialize the DOM tree into a string or file.
5. If you know the content of the XML document in advance, you can use RegExp. If you are affected by newlines when scanning with RegExp, you may want to delete all newlines. However, this approach is a "last-hand" because if the XML code changes slightly, the approach may fail.
Parses and manipulates the responseText property containing HTML documents
Note: HTML is allowed to be parsed through the XMLHttpRequest.responseXML attribute in the W3C XMLHttpRequest specification. For more details, please read HTML in XMLHttpRequest.
If you use XMLHttpRequest to get an HTML page from the remote end, all HTML tags are stored in the responseText property as a string, making it difficult to manipulate and parse these tags. There are three main ways to parse these HTML tags:
1. Use the XMLHttpRequest.responseXML property.
2. Inject content into a document fragment through fragment.body.innerHTML and iterate through 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 newlines when scanning with RegExp, you may want to delete all newlines. However, this approach is a "last-hand" because if the HTML code changes slightly, the approach may fail.
Handling binary data
Although XMLHttpRequest is generally used to send and receive text data, it can actually send and accept binary content. There are many well-tested ways to force binary data to be sent using XMLHttpRequest. The .overrideMimeType() method of XMLHttpRequest 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 stringoReq.overrideMimeType("text/plain; charset=x-user-defined");/* ... */The responseType property has been 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("GET", url, true);oReq.responseType = "arraybuffer";oReq.send();Accept binary data using JavaScript type array
You can change the data type of a response returned from the server by setting the responseType property of an XMLHttpRequest object. The available attribute values are empty strings (default), "arraybuffer", "blob", "document", and "text". The values of the response attribute will vary depending on the responseType property's value, which may be an ArrayBuffer, Blob, Document, string, or NULL (if the request is not completed or failed)
The following example reads a binary image file, and an array of 8-bit unsigned integers is created from the binary native bytes 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++) { // Operation for each byte in the array} }};oReq.send(null);In addition to the above method, you can also use the BlobBuilder API to directly add arraybuffer data to a Blob object. Since the API is still in the experimental stage, a specific prefix needs to be added:
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 can load binary data from the specified URL and return 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 != 200) return /'/'; return req.responseText;}The most wonderful operation is in the fifth line, which rewrites the default MIME type, 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 directly return the unprocessed bytecode.
var filestream = load_binary_resource(url);var abyte = filestream.charCodeAt(x) & 0xff; // thrown away high-bit byte(f7)
The above example obtains the bytes at x from the binary data returned by the request. The valid offset range is 0 to filestream.length-1.
Check out the download file using XMLHttpRequest for details and view the download file.
Send binary data
The send method of the XMLHttpRequest object has been enhanced, and binary data can be sent simply by passing an ArrayBuffer, Blob, or File object.
The following example creates a text file and sends the file to the server using the POST method. You can also use other binary data types other than the text file.
var oReq = new XMLHttpRequest();oReq.open("POST", url, true);oReq.onload = function (oEvent) { // After uploading is completed.};var bb = new BlobBuilder(); // A suitable prefix is required: window.MozBlobBuilder or window.WebKitBlobBuilderbb.append(/'abc123/');oReq.send(bb.getBlob(/'text/plain/'));Send array of types as binary data
You can send JavaScript type arrays 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);The above example creates a 512-byte 8-bit integer array and sends it. Of course, you can also send any binary data.
Monitor progress
Progress event monitoring that supports DOM is for XMLHttpRequest transmission and follows the Web API progress event specification: These events implement the ProgressEvent interface.
var req = new XMLHttpRequest();//Upload listen 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; ... } else { // Unable to compute progress information since the total size is unknown }}Note: You need to add event listening before requesting to call open(). Otherwise the progress event will not be triggered.
In the previous example, the progress event is specified to be processed by the updateProgress() function and receives total number of transmitted bytes total and already transmitted loaded , which is the overall length (bytes) of the data transmitted from the "Content-Length" header. However, if the value of the lengthComputable property is false, then the total number of bytes is unknown and the total value is 0. If the length is known, the lengthComputable property is true
The progress event exists in both download and upload transmissions. The download-related event is triggered on the XMLHttpRequest object, just like the example above. Upload related events are triggered on the XMLHttpRequest.upload object, like this:
var req = new XMLHttpRequest();//Download listener 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.
Use the loadend event to detect all three load end conditions (abort, load, error):
req.addEventListener("loadend", loadEnd, false);
It should be noted that there is no way to know exactly what condition the information received by the loadend event is caused by the operation termination; however, you can use this event to handle it 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 called, a single loadstart event is triggered. When the server's response is loading, the XMLHttpRequest object will experience a progress event, usually every 50 milliseconds, so these events can be used 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 will be triggered.
There are 3 cases where HTTP requests cannot be completed, corresponding to 3 events. If the request timeout, the timeout event will be triggered. If the request abort, the abort event will be triggered. Network errors like too many redirects prevent the request from completing, but when these happen, an error event is triggered.
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())){ //Detection whether progress events are supported var request = new XMLHttpRequest(); request.onprogress = function (e) { if(e.lengthComputable){ progress.innerHTML = Math.round(100* e.loaded/ e.total) + /'%/'; } }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.