ajax 和 mock 數據

ajax

ajax是一種技術方案,但並非一種新技術。它依賴的是現有的CSS/HTML/Javascript,而其中最核心的依賴是瀏覽器提供的XMLHttpRequest對象,是這個對象使得瀏覽器能夠發出HTTP請求與接收HTTP響應。 實如今頁面不刷新的狀況下和服務端進行數據交互。javascript

做用:
傳統的網頁(不使用ajax)。若是須要更新內容,必須從新加載整個網頁,而經過使用ajax能夠在後臺與服務器進行少許數據交換,可使網頁實現異步更新。這意味着能夠在不從新加載整個網頁的狀況下,對網頁的某部分進行更新。html

實現方式

  • XMLHttpRequest對象
  • fetch(兼容性不如XMLHttpRequest)
    兼容性查詢

範例

GET 範例

//異步GET var xhr = new XMLHttpRequest() xhr.open('GET','/login?username=evenyao&password=123',true) //get類型 數據須要拼接成url放到?後面 xhr.send() console.log('readyState:',xhr.readyState) xhr.addEventListener('readystatechange',function(){ //或者使用xhr.onload = function() //查看readyState狀態 console.log('readyState:',xhr.readyState) }) xhr.addEventListener('load',function(){ console.log(xhr.status) if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){ var data = xhr.responseText console.log(data) }else{ console.log('error') } }) xhr.onerror = function(){ console.log('error') } //等同代碼 var xhr = new XMLHttpRequest() xhr.open('GET','/login?username=evenyao&password=123',true) xhr.send() xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){ console.log(xhr.responseText) }else{ console.log('error') } } } xhr.onerror = function(){ console.log('error') } 

 

POST 範例

//異步POST var xhr = new XMLHttpRequest() xhr.open('POST','/login',true) //post拼接數據放掉send裏面 //post拼接數據放掉send裏面 xhr.send(makeUrl({ username:'evenyao', password:'123' })) xhr.addEventListener('load',function(){ console.log(xhr.status) if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){ var data = xhr.responseText console.log(data) }else{ console.log('error') } }) xhr.onerror = function(){ console.log('error') } //makeUrl拼接函數 function makeUrl(obj){ var arr = [] for(var key in obj){ arr.push(key + '=' + obj[key]) } return arr.join('&') } 

 

封裝 ajax

//封裝 ajax function ajax(opts){ var url = opts.url //若是有類型就使用用戶輸入的類型; 若是沒有,默認爲後面的 var type = opts.type || 'GET' var dataType = opts.dataType || 'json' var onsuccess = opts.onsuccess || function(){} var onerror = opts.onerror || function(){} var data = opts.data || {} //data序列化 var dataStr = [] for(var key in data){ dataStr.push(key + '=' + data[key]) } dataStr = dataStr.join('&') //GET類型 使用url拼接 if(type === 'GET'){ url += '?' + dataStr } //XMLHttpRequest對象建立 var xhr = new XMLHttpRequest() xhr.open(type,url,true) xhr.onload = function(){ if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ //成功 //若是返回的數據類型是json,就解析成json格式 if(dataType === 'json'){ onsuccess(JSON.parse(xhr.responseText)) }else{ onsuccess(xhr.responseText) } }else{ onerror() } } //若是斷網,也會執行onerror() xhr.onerror = onerror() //POST類型 if(type === 'POST'){ xhr.send(dataStr) }else{ xhr.send() } } ajax({ url:'http://xxx', type: 'POST', data: { city: '北京' }, onsuccess: function(ret){ console.log(ret) render(ret) }, onerror: function(){ console.log('服務器異常') showError() } }) function render(json){ } function showError(){ } 

 

參考

你真的會使用XMLHttpRequest嗎?
Ajax狀態值及狀態碼java

 

關於如何mock數據

http-server

本地使用http-server node工具啓動一個靜態服務器
如下是已經寫好的ajax用法,這裏採用GET類型,使用xhr.open('GET','/hello2.json',true)
在已經安裝好nodehttp-server的狀況下,先cd到對應的文件夾。而後經過http-server啓動本地server。node

 
 


經過訪問127.0.0.1:8080/indexl.html,並進入控制檯,便可看到mock結果git

 

 

具體ajax用法代碼:github

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script type="text/javascript"> // ajax GET var xhr = new XMLHttpRequest() xhr.open('GET','/hello2.json',true) xhr.send() xhr.onload = function(){ console.log(xhr.status) if((xhr.status >= 200 && xhr.status < 300)|| xhr.status === 304){ var data = xhr.responseText console.log(data) console.log(JSON.parse(data)) }else{ console.log('error') } } xhr.onerror = function(){ console.log('error') } </script> </body> </html> 

模擬接口的json文件內容:ajax

//hello2.json 內容 { "name": "go", "success": true, "data": [ "70", "80", "90", "年代" ] } 

 

github

在github上面寫一個服務器進行mock
具體和本地區別不大,只是須要注意模擬接口的地址,由於域名是github.com,因此前面還須要加項目名,詳情見github/mocktest裏面的README.md
測試:
github pagesjson

 

線上mock

使用easy-mock.com進行mock數據segmentfault

  1. 進入easy-mock.com,登陸註冊帳號以後進入建立項目,輸入名稱而後建立瀏覽器

     
     

     

     

  2. 進入建立好的項目
     
     
  3. 選擇建立接口
     

     

  4. 填寫類型(get/post)、描述、並輸入JSON格式的內容,點擊建立
     
     
  5. 生成連接,複製該連接
     
     
  6. 將該連接粘貼到以前寫好的ajax用法的xhr.open('GET','',true)當中

     
     
     
    7.  打開頁面,進入控制檯查看mock結果
相關文章
相關標籤/搜索