1.ajax 是什么?有什么作用啡省?
ajax主要是實現(xiàn)頁面和web服務器之間數(shù)據(jù)的異步傳輸娜睛。
不采用ajax的頁面,當用戶在頁面發(fā)起請求時卦睹,就要進行整個頁面的刷新畦戒,刷新快慢取決于服務器的處理快慢。在這個過程中用戶必須得等待结序,不能進行其他操作障斋;采用ajax的頁面,可以實現(xiàn)頁面的局部更新徐鹤,并且發(fā)起請求后垃环,用戶還可以進行頁面上的其他操作;
2.前后端開發(fā)聯(lián)調(diào)需要注意哪些事情返敬?后端接口完成前如何 mock 數(shù)據(jù)遂庄?
需要注意的事情:
- 約定數(shù)據(jù):確定需要傳輸?shù)臄?shù)據(jù)及數(shù)據(jù)類型
- 約定接口:確定接口名稱及請求和響應的格式,請求的參數(shù)名稱劲赠、響應的數(shù)據(jù)格式涛目;
如何mock數(shù)據(jù): - 方法一:使用xampp等工具,搭建本地web服務器凛澎,編寫php腳本提供數(shù)據(jù)
- 方法二:使用server-mock模擬數(shù)據(jù)
3.點擊按鈕霹肝,使用 ajax 獲取數(shù)據(jù),如何在數(shù)據(jù)到來之前防止重復點擊?
- 使用button的disabled屬性塑煎,配合setTimeout 0沫换,使在數(shù)據(jù)到來之前按鈕都不能被點擊
ele.addEventListener('click',function(){
this.disabled=true;
ajax();
setTimeout(this.disabled=false,0);
});
- 設置一個開關(guān),初始狀態(tài)是false最铁,發(fā)生點擊事件后苗沧,開關(guān)狀態(tài)置為true刊棕,直到ajax請求完成后,開關(guān)狀態(tài)才會被重新置為false待逞。
var lock = false;
ele.addEventListener('click',function(){
if(!lock){
lock = true;
ajax();
lock = false;
}
});
代碼
1.封裝一個 ajax 函數(shù)甥角,能通過如下方式調(diào)用
function ajax(opts) {
// 做參數(shù)兼容
opts.success = opts.success || function(){};
opts.error = opts.error || function(){};
opts.type = opts.type || 'get';
opts.dataType = opts.dataType || 'json';
opts.data = opts.data || {};
var dataStr = '';
for (var key in opts.data) {
dataStr += key + '=' + opts.data[key] + '&';
}
dataStr = dataStr.substr(0, dataStr.length - 1);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if(xmlhttp.status === 200){
if(opts.dataType === 'text'){
opts.success(xmlhttp.responseText);
}
if(opts.dataType === 'json'){
var json = JSON.parse(xmlhttp.responseText);
opts.success(json);
}
}else{
opts.error();
}
}
};
if (opts.type.toLowerCase() === 'post') {
xmlhttp.open(opts.type, opts.url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(dataStr);
}
if (opts.type.toLowerCase() === 'get') {
xmlhttp.open(opts.type, opts.url + '?' + dataStr, true);
xmlhttp.send();
}
}
調(diào)用方式:
document.querySelector('#btn').addEventListener('click', function(){
ajax({ url: 'getData.php', //接口地址
type: 'get', // 類型,post 或者 get,
data: {
username: 'xiaoming',
password: 'abcd1234'
},
success: function(ret){
console.log(ret); // {status: 0}
},
error: function(){
console.log('出錯了')
}
})
});
代碼
1.實現(xiàn)如下加載更多的功能
本地測試通過GitHub上代碼地址
2.實現(xiàn)注冊表單驗證功能
xampp上測試通過GitHub上代碼地址