Front words
The response subject types we receive can take many forms, including string String, ArrayBuffer object, binary Blob object, JSON object, javascirpt file and Document object representing XML document. Next, we will decode the response for different types of subjects.
attribute
Before introducing response decoding, understand XHR object Properties. Generally, if the received data is a string, use responseText, which is also the most commonly used attribute for receiving data. But if you get other types of data, responseText might not be appropriate.
[responseText]
The responseText property returns the string received from the server, which is read-only. If the request is unsuccessful or the data is incomplete, the attribute will be equal to null.
If the data format returned by the server is JSON, string, javascript or XML, you can use the responseText attribute
[response]
The response attribute is read-only and returns the received data volume. Its type can be ArrayBuffer, Blob, Document, JSON object, or a string, depending on the value of the XMLHttpRequest.responseType attribute
If the request is unsuccessful or the data is incomplete, the attribute will be null
[Note] IE9 - Browser does not support
[responseType]
The responseType attribute is used to specify the type of server return data (xhr.response)
"": String (default value) "Arraybuffer": ArrayBuffer object "Blob": Blob object "Document": Document object "Json": JSON object "text": string
[responseXML]
The responseXML attribute returns the Document object received from the server, which is read-only. If the request is unsuccessful, or the data is incomplete, or cannot be parsed into XML or HTML, the attribute is equal to null.
[overrideMimeType()]
This method is used to specify the MIME type of data returned by the server. This method must be called before send()
Traditionally, if you want to retrieve binary data from the server, you have to use this method to artificially disguise the data type as text data.
However, this method is cumbersome, and after upgrading the version of XMLHttpRequest, the method of specifying responseType is generally adopted.
Character string
If the result returned by the server is a string, parse it directly using the responseText attribute
The encapsulation of ajax() functions is already in place. Last blog As described in detail, I will not repeat it here. Direct call ajax.js Use
<button id="btn">Get response</button> <div id="result"></div> <script> btn.onclick = function(){ ajax({ url:'p1.php', callback:function(data){ result.innerHTML = data; } }) } </script>
<?php //Setting the content of the page html The encoding format is utf-8,Content is plain text header("Content-Type:text/plain;charset=utf-8"); echo 'Hello, World'; ?>
JSON
The most common way to use ajax is to use JSON strings, which can be parsed directly using the responseText attribute.
<button id="btn">Get response</button> <div id="result"></div> <script> btn.onclick = function(){ ajax({ url:'p2.php', callback:function(data){ var obj = JSON.parse(data); var html = ''; for(var i = 0; i < obj.length; i++){ html+= '<div>' + obj[i].title + ':' + obj[i].data + '</div>'; } result.innerHTML = html; html = null; } }) } </script>
<?php header("Content-Type:application/json;charset=utf-8"); $arr = [['title'=>'colour','data'=>'gules'],['title'=>'size','data'=>'inch'],['title'=>'weight','data'=>'Kg.']]; echo json_encode($arr); ?>
XML
Before the advent of JSON, XML was a commonly used data transmission format on the network, but it was less used because of its heavy format.
When receiving an XML document, use responseXML to parse the data
<button id="btn">Get response</button> <div id="result"></div> <script> btn.onclick = function(){ ajax({ url:'p3.xml', callback:function(data){ var obj = data.getElementsByTagName('CD'); var html = ''; for(var i = 0; i < obj.length; i++){ html += '<div>Record:' + obj[i].getElementsByTagName('TITLE')[0].innerHTML + ';Singer:' + obj[i].getElementsByTagName('ARTIST')[0].innerHTML + '</div>'; } result.innerHTML = html; html = null; } }) } function ajax(obj){ //method by ajax Submitted by default'get'Method obj.method = obj.method || 'get'; //Establish xhr object var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //Asynchronous Acceptance Response xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //callback For callback functions, there is no callback if not set obj.callback && obj.callback(xhr.responseXML); } } } //Create a data string to hold the data to be submitted var strData = ''; obj.data = true; if(obj.method == 'post'){ for(var key in obj.data){ strData += '&' + key + "=" + obj.data[key]; } //Get rid of redundancy'&' strData = strData.substring(1); xhr.open('post',obj.url,true); //Setting the request header xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); //Send request xhr.send(strData); }else{ //If it is get In this way, the characters are compiled for(var key in obj.data){ strData += '&' + encodeURIComponent(key) + "=" + encodeURIComponent(obj.data[key]); } //Get rid of redundancy'&',And increase the random number to prevent caching strData = strData.substring(1) + '&'+Number(new Date()); xhr.open('get',obj.url+'?'+strData,true); //Send request xhr.send(); } } </script>
<CATALOG data-livestyle-extension="available"> <CD> <TITLE>Rosemary</TITLE> <ARTIST>Jay Chou</ARTIST> </CD> <CD> <TITLE>Chengdu</TITLE> <ARTIST>Zhao Lei</ARTIST> </CD> <CD> <TITLE>It's time</TITLE> <ARTIST>Stefanie Sun</ARTIST> </CD> </CATALOG>
js
Using ajax, you can also receive js files. responseText is still used to receive data, but eval() is used to execute the code
<button id="btn">Get response</button> <div id="result"></div> <script> btn.onclick = function(){ ajax({ url:'p4.js', callback:function(data){ eval(data); var html = ''; for(var key in obj){ html += '<div>' + key + ':' + obj[key] + '</div>'; } result.innerHTML = html; html = null; } }) } </script>
var obj = { 'Full name':'Little match', 'Age':28, 'Gender':'male' }
blob
In javascript, Blob Usually it represents binary data. But in practical Web applications, Blob is more about uploading and downloading pictures in binary form, although it can realize the binary transmission of almost any file.
To receive BLOB data using ajax, you need to use response to receive it, and set the responseType to'blob'
[Note] To be fully compatible with IE10 + browsers, you need to set xhr.responseType between xhr.open() and xhr.send() methods
<button id="btn">Get response</button> <div id="result"></div> <script> btn.onclick = function(){ ajax({ url:'p5.gif', callback:function(data){ var img = document.createElement('img'); img.onload = function(){ URL.revokeObjectURL(img.src); } img.src = URL.createObjectURL(data); if(!result.innerHTML){ result.appendChild(img); } }, method:'post' }) } function ajax(obj){ //method by ajax Submitted by default'get'Method obj.method = obj.method || 'get'; //Establish xhr object var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //Asynchronous Acceptance Response xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //callback For callback functions, there is no callback if not set obj.callback && obj.callback(xhr.response); } } } //Create a data string to hold the data to be submitted var strData = ''; obj.data = true; if(obj.method == 'post'){ for(var key in obj.data){ strData += '&' + key + "=" + obj.data[key]; } //Get rid of redundancy'&' strData = strData.substring(1); xhr.open('post',obj.url,true); xhr.responseType = 'blob'; //Setting the request header xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); //Send request xhr.send(strData); }else{ //If it is get In this way, the characters are compiled for(var key in obj.data){ strData += '&' + encodeURIComponent(key) + "=" + encodeURIComponent(obj.data[key]); } //Get rid of redundancy'&',And increase the random number to prevent caching strData = strData.substring(1) + '&'+Number(new Date()); xhr.open('get',obj.url+'?'+strData,true); xhr.responseType = 'blob'; //Send request xhr.send(); } } </script>
arraybuffer
arraybuffer Represents a segment of memory that stores binary data, while a blob is used to represent binary data. Receive arraybuffer through ajax and convert it to BLOB data for further operation
ResponsseType is set to arraybuffer, and then response is passed as a parameter of the new Blob() constructor to generate the blob object
<button id="btn">Get response</button> <div id="result"></div> <script> btn.onclick = function(){ ajax({ url:'p5.gif', callback:function(data){ var img = document.createElement('img'); img.onload = function(){ URL.revokeObjectURL(img.src); } img.src = URL.createObjectURL(new Blob([data])); if(!result.innerHTML){ result.appendChild(img); } } }) } function ajax(obj){ //method by ajax Submitted by default'get'Method obj.method = obj.method || 'get'; //Establish xhr object var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //Asynchronous Acceptance Response xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //callback For callback functions, there is no callback if not set obj.callback && obj.callback(xhr.response); } } } //Create a data string to hold the data to be submitted var strData = ''; obj.data = true; if(obj.method == 'post'){ for(var key in obj.data){ strData += '&' + key + "=" + obj.data[key]; } //Get rid of redundancy'&' strData = strData.substring(1); xhr.open('post',obj.url,true); //Setting the request header xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); xhr.responseType = 'arraybuffer'; //Send request xhr.send(strData); }else{ //If it is get In this way, the characters are compiled for(var key in obj.data){ strData += '&' + encodeURIComponent(key) + "=" + encodeURIComponent(obj.data[key]); } //Get rid of redundancy'&',And increase the random number to prevent caching strData = strData.substring(1) + '&'+Number(new Date()); xhr.open('get',obj.url+'?'+strData,true); xhr.responseType = 'arraybuffer'; //Send request xhr.send(); } } </script>