眾所周知,在日常開發(fā)中,前后端分離是最常見的開發(fā)模式,前端完成頁面渲染,后端提供接口數(shù)據(jù)。
但是起初項目剛開始,后端還沒有寫好接口數(shù)據(jù),前端要構建頁面,還得考慮結構以及后期真實數(shù)據(jù)的問題。
所以前后端統(tǒng)一接口數(shù)據(jù)和格式是必要的。
而當統(tǒng)一好接口數(shù)據(jù)和格式后,前端就可以通過mock.js來模擬對應格式的數(shù)據(jù),以此來完成頁面的搭建,當后端完成接口和數(shù)據(jù)后,因為前期數(shù)據(jù)格式都是規(guī)范好的,所以只要去除掉mock.js那部分即可,而不需要再更改界面。
那么說了這么多,mock.js到底是什么?
根據(jù)官網(wǎng)簡單的解釋來說,就是:攔截ajax請求,模擬返回自定義格式的數(shù)據(jù),實現(xiàn)前后端分離。
說的這么厲害,那么我們來看看具體用法。
這次先看看在原生中怎么使用,下次介紹在vue中的使用。
普通不涉及框架的項目中安裝mock.js推薦使用bower安裝:
npm install bower -g
bower install mockjs --save
具體使用:
<!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>mock js-demo1</title></head> <body> </body> </html><script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script><script src="js/ajax.js"></script><script type="text/javascript" src="./bower_components/mockjs/dist/mock.js"></script><script> Mock.mock('http://api.com', { 'users|5': [ { 'name': '@cname', //中文名稱 'age|1-100': 100, //100以內(nèi)隨機整數(shù) 'birthday': '@date("yyyy-MM-dd")', //日期 'city': '@city(true)' //中國城市 }] }); // //JQuery方式 $.ajax({ url: 'http://api.com', dataType: 'json' }).done(function (data, status, xhr) { console.log( JSON.stringify(data, null, 4) ) }); //原生ajax方式 function ajax(method, url, params, isAsync) { //創(chuàng)建對象 xhr = new XMLHttpRequest(); //設置請求參數(shù) xhr.open(method, url, isAsync); //回調(diào)函數(shù) xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); } } //發(fā)送請求 xhr.send(); } ajax('get','http://api.com','', true);</script>這里我引入了通過bower下載的mock.js,然后給mockjs給定一個請求地址(如果有可以給定真實地址,沒有可以寫個假地址,只要和ajax請求地址一致即可),然后在mock的第二個參數(shù)中定義了數(shù)據(jù)格式,是個隨機五位的數(shù)組對象,包括姓名、年齡、生日、地址
然后通過ajax正常請求地址,然后返回值就會收到mock.js的攔截,而返回我們自定義格式的數(shù)據(jù),而不是后端數(shù)據(jù)
新聞熱點
疑難解答
圖片精選