Home > Article > Web Front-end > ajax response decoding
The response body type we receive can be in many forms, including StringString, ArrayBuffer Object, binary Blob object, JSON object, javascirpt file and Document object representing the XML document, etc. The following will carry out corresponding response decoding for different subject types
Before introducing response decoding, You must first understand the properties of the XHR object. Generally, if the received data is a string, just use responseseText, which is also the most commonly used attribute for receiving data. But if other types of data are obtained, it may not be appropriate to use responseText
[responseText]
The responseText attribute returns the string received from the service server, This property is read-only. If this request is unsuccessful or the data is incomplete, this attribute will equal null.
If the data format returned by the server is JSON, string, javascript or XML, you can use the responseText attribute
[response]
response attribute It is read-only and returns the received data body. Its type can be ArrayBuffer, Blob, Document, JSON object, or a string, which is determined by the value of the XMLHttpRequest.responseType attribute
If this request is unsuccessful or the data is incomplete, this attribute will be equal to null
[Note]IE9-browser does not support
[responseType]
The responseType attribute is used to specify the type of data returned by the server (xhr.response)
“”:字符串(默认值) “arraybuffer”:ArrayBuffer对象 “blob”:Blob对象 “document”:Document对象 “json”:JSON对象 “text”:字符串
[responseXML]
The responseXML attribute returns the Document object received from the server. This attribute is read-only. If this request is unsuccessful, or the data is incomplete, or cannot be parsed as XML or HTML, this attribute is equal to null
【overrideMimeType()】
This method is used to specify the data returned by the server MIME type. This method must be called before send(). Traditionally, if you want to retrieve binary data from the server, you must use this method to artificially change the
data typeDisguised as text data However, this method is very troublesome. After the XMLHttpRequest version is upgraded, the method of specifying responseType is generally used
String
Regarding the encapsulation of the ajax()
function, it has been introduced in detail in the previous blog, here I won’t go into details. Directly call ajax.js using
<button id="btn">取得响应</button><p id="result"></p><script>btn.onclick = function(){ ajax({ url:'p1.php', callback:function(data){ result.innerHTML = data; } }) }</script>
<?php //设置页面内容的html编码格式是utf-8,内容是纯文本 header("Content-Type:text/plain;charset=utf-8"); echo '你好,世界';?>
<button id="btn">取得响应</button><p id="result"></p><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+= '<p>' + obj[i].title + ':' + obj[i].data + '</p>'; } result.innerHTML = html; html = null; } }) }</script>
<?php header("Content-Type:application/json;charset=utf-8"); $arr = [['title'=>'颜色','data'=>'红色'],['title'=>'尺寸','data'=>'英寸'],['title'=>'重量','data'=>'公斤']]; echo json_encode($arr);?>
When receiving XML documents, use responseXML to parse the data
<button id="btn">取得响应</button><p id="result"></p><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 += '<p>唱片:' + obj[i].getElementsByTagName('TITLE')[0].innerHTML + ';歌手:' + obj[i].getElementsByTagName('ARTIST')[0].innerHTML + '</p>'; } result.innerHTML = html; html = null; } }) }function ajax(obj){ //method为ajax提交的方式,默认为'get'方法 obj.method = obj.method || 'get'; //创建xhr对象 var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //异步接受响应 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //callback为回调函数,如果不设置则无回调 obj.callback && obj.callback(xhr.responseXML); } } } //创建数据字符串,用来保存要提交的数据 var strData = ''; obj.data = true; if(obj.method == 'post'){ for(var key in obj.data){ strData += '&' + key + "=" + obj.data[key]; } //去掉多余的'&' strData = strData.substring(1); xhr.open('post',obj.url,true); //设置请求头 xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); //发送请求 xhr.send(strData); }else{ //如果是get方式,则对字符进行编成 for(var key in obj.data){ strData += '&' + encodeURIComponent(key) + "=" + encodeURIComponent(obj.data[key]); } //去掉多余的'&',并增加随机数,防止缓存 strData = strData.substring(1) + '&'+Number(new Date()); xhr.open('get',obj.url+'?'+strData,true); //发送请求 xhr.send(); } }</script>
<CATALOG data-livestyle-extension="available"><CD> <TITLE>迷迭香</TITLE> <ARTIST>周杰伦</ARTIST></CD><CD> <TITLE>成都</TITLE> <ARTIST>赵雷</ARTIST></CD><CD> <TITLE>是时候</TITLE> <ARTIST>孙燕姿</ARTIST></CD></CATALOG>
<button id="btn">取得响应</button><p id="result"></p><script>btn.onclick = function(){ ajax({ url:'p4.js', callback:function(data){ eval(data); var html = ''; for(var key in obj){ html += '<p>' + key + ':' + obj[key] + '</p>'; } result.innerHTML = html; html = null; } }) }</script>
var obj = { '姓名':'小火柴', '年龄':28, '性别':'男'}
, Blob is more of a picturebinary formuploadand download, although it can achieve binary transmission of almost any file To use ajax to receive blob data, 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 in xhr.open( ) and the xhr.send() method
<button id="btn">取得响应</button><p id="result"></p><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为ajax提交的方式,默认为'get'方法 obj.method = obj.method || 'get'; //创建xhr对象 var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //异步接受响应 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //callback为回调函数,如果不设置则无回调 obj.callback && obj.callback(xhr.response); } } } //创建数据字符串,用来保存要提交的数据 var strData = ''; obj.data = true; if(obj.method == 'post'){ for(var key in obj.data){ strData += '&' + key + "=" + obj.data[key]; } //去掉多余的'&' strData = strData.substring(1); xhr.open('post',obj.url,true); xhr.responseType = 'blob'; //设置请求头 xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); //发送请求 xhr.send(strData); }else{ //如果是get方式,则对字符进行编成 for(var key in obj.data){ strData += '&' + encodeURIComponent(key) + "=" + encodeURIComponent(obj.data[key]); } //去掉多余的'&',并增加随机数,防止缓存 strData = strData.substring(1) + '&'+Number(new Date()); xhr.open('get',obj.url+'?'+strData,true); xhr.responseType = 'blob'; //发送请求 xhr.send(); } }</script>
arraybuffer代表储存二进制数据的一段内存,而blob则用于表示二进制数据。通过ajax接收arraybuffer,然后将其转换为blob数据,从而进行进一步的操作
responseType设置为arraybuffer,然后将response作为new Blob()构造函数的参数传递,生成blob对象
<button id="btn">取得响应</button><p id="result"></p><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为ajax提交的方式,默认为'get'方法 obj.method = obj.method || 'get'; //创建xhr对象 var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //异步接受响应 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //callback为回调函数,如果不设置则无回调 obj.callback && obj.callback(xhr.response); } } } //创建数据字符串,用来保存要提交的数据 var strData = ''; obj.data = true; if(obj.method == 'post'){ for(var key in obj.data){ strData += '&' + key + "=" + obj.data[key]; } //去掉多余的'&' strData = strData.substring(1); xhr.open('post',obj.url,true); //设置请求头 xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); xhr.responseType = 'arraybuffer'; //发送请求 xhr.send(strData); }else{ //如果是get方式,则对字符进行编成 for(var key in obj.data){ strData += '&' + encodeURIComponent(key) + "=" + encodeURIComponent(obj.data[key]); } //去掉多余的'&',并增加随机数,防止缓存 strData = strData.substring(1) + '&'+Number(new Date()); xhr.open('get',obj.url+'?'+strData,true); xhr.responseType = 'arraybuffer'; //发送请求 xhr.send(); } }</script>
The above is the detailed content of ajax response decoding. For more information, please follow other related articles on the PHP Chinese website!