標籤:姓名 uri 回調 mic fun plain title 編碼 encodeuri
前面的話
我們接收到的響應主體類型可以是多種形式的,包括字串String、ArrayBuffer對象、二進位Blob對象、JSON對象、javascirpt檔案及表示XML文檔的Document對象等。下面將針對不同的主體類型,進行相應的響應解碼
屬性
在介紹響應解碼之前,要先瞭解XHR對象的屬性。一般地,如果接受的資料是字串,使用responseText即可,這也是最常用的用於接收資料的屬性。但如果擷取了其他類型的資料,使用responseText可能就不太合適了
【responseText】
responseText屬性返回從伺服器接收到的字串,該屬性為唯讀。如果本次請求沒有成功或者資料不完整,該屬性就會等於null。
如果伺服器返回的資料格式是JSON、字串、javascript或XML,都可以使用responseText屬性
【response】
response屬性為唯讀,返回接收到的資料體。它的類型可以是ArrayBuffer、Blob、Document、JSON對象、或者一個字串,這由XMLHttpRequest.responseType屬性的值決定
如果本次請求沒有成功或者資料不完整,該屬性就會等於null
[注意]IE9-瀏覽器不支援
【responseType】
responseType屬性用來指定伺服器返回資料(xhr.response)的類型
“”:字串(預設值)“arraybuffer”:ArrayBuffer對象“blob”:Blob對象“document”:Document對象“json”:JSON對象“text”:字串
【responseXML】
responseXML屬性返回從伺服器接收到的Document對象,該屬性為唯讀。如果本次請求沒有成功,或者資料不完整,或者不能被解析為XML或HTML,該屬性等於null
【overrideMimeType()】
該方法用來指定伺服器返回資料的MIME類型。該方法必須在send()之前調用
傳統上,如果希望從伺服器取回位元據,就要使用這個方法,人為將資料類型偽裝成文本資料
但是,這種方法很麻煩,在XMLHttpRequest版本升級以後,一般採用指定responseType的方法
字串
如果伺服器返回的結果是一個字串,則直接使用responseText屬性解析即可
關於ajax()函數的封裝,已經在上一篇部落格中詳細介紹過,這裡就不再贅述。直接調用ajax.js使用
<button id="btn">取得響應</button><div id="result"></div><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 ‘你好,世界‘;?>
JSON
使用ajax最常用的傳輸方式就是使用JSON字串,直接使用responseText屬性解析即可
<button id="btn">取得響應</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‘=>‘顏色‘,‘data‘=>‘紅色‘],[‘title‘=>‘尺寸‘,‘data‘=>‘英寸‘],[‘title‘=>‘重量‘,‘data‘=>‘公斤‘]]; echo json_encode($arr);?>
XML
XML在JSON出現之前,是網路上常用的資料轉送格式,但由於其格式較笨重,所以用的較少
接收XML文檔時,使用responseXML來對資料進行解析
<button id="btn">取得響應</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>唱片:‘ + obj[i].getElementsByTagName(‘TITLE‘)[0].innerHTML + ‘;歌手:‘ + obj[i].getElementsByTagName(‘ARTIST‘)[0].innerHTML + ‘</div>‘; } 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>
js
使用ajax也可以接收js檔案。仍然使用responseText來接收資料,但要使用eval()來執行代碼
<button id="btn">取得響應</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 = { ‘姓名‘:‘小火柴‘, ‘年齡‘:28, ‘性別‘:‘男‘}
blob
在javascript中,Blob通常表示位元據。但在實際Web應用中,Blob更多是圖片二進位形式的上傳與下載,雖然其可以實現幾乎任意檔案的二進位傳輸
使用ajax接收blob資料,需要使用response來接收,並且將responseType設定為‘blob‘
[注意]要完全相容IE10+瀏覽器,需要將xhr.responseType設定在xhr.open()和xhr.send()方法之間
<button id="btn">取得響應</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為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
arraybuffer代表儲存位元據的一段記憶體,而blob則用於表示位元據。通過ajax接收arraybuffer,然後將其轉換為blob資料,從而進行進一步的操作
responseType設定為arraybuffer,然後將response作為new Blob()建構函式的參數傳遞,產生blob對象
<button id="btn">取得響應</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為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>
深入理解ajax系列第三篇