1.ajax 是什么和悦?有什么作用遍膜?
- AJAX = Asynchronous JavaScript and XML:異步的 JavaScript 和 XML
- 實(shí)現(xiàn)網(wǎng)頁的異步加載郎仆,局部刷新網(wǎng)頁。當(dāng)在向服務(wù)器獲取新數(shù)據(jù)時(shí)不需要刷新整個(gè)網(wǎng)頁捺癞,提高用戶體驗(yàn)憾赁。
2.前后端開發(fā)聯(lián)調(diào)需要注意哪些事情?后端接口完成前如何 mock 數(shù)據(jù)赠橙?
- 注意事項(xiàng)
- 約定數(shù)據(jù):有哪些需要傳輸?shù)臄?shù)據(jù)耽装,數(shù)據(jù)類型是什么
- 約定接口:確定接口名稱及請求和響應(yīng)的格式,請求的參數(shù)名稱期揪、響應(yīng)的數(shù)據(jù)格式
- server-mock
3.點(diǎn)擊按鈕掉奄,使用 ajax 獲取數(shù)據(jù),如何在數(shù)據(jù)到來之前防止重復(fù)點(diǎn)擊?
- 創(chuàng)建一個(gè)變量作為狀態(tài)鎖(標(biāo)志位),初始為true姓建,發(fā)送后置為false诞仓,若為false直接return
var AjaxLocking = true;
//點(diǎn)擊事件監(jiān)聽函數(shù)
xxx.addEventListener('clock',function(){
if(!AjaxLocking){
return;
}
xhr.onreadystatechange = function(){ //事件
if(xhr.readyState === 4){
//...
AjaxLocking = true;
}
}
xhr.open()
xhr.send()
AjaxLocking = false;
})
4.封裝一個(gè) ajax 函數(shù),能通過如下方式調(diào)用速兔。后端在本地使用server-mock來 mock 數(shù)據(jù)
function ajax(opts){
opts.success = opts.success || function () {};
opts.error = opts.error || function () {};
opts.type = opts.type || 'get';
opts.dataType = opts.dataType || {};
opts.data = opts.data || {};
var dataStr = '';
for (var key in opts.data)
{
dataStr += key + '=' + opts.data[key] + '&';
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200 || xmlhttp.status == 304) {
if (opts.dataType === 'text') {
opts.success(xmlhttp.responseText);
}
if (opts.dataType === 'json') {
var json = JSON.parse(xmlhttp.responseText);
opts.success(json);
}
} else {
opts.error();
}
}
};
dataStr = dataStr.substr(0, dataStr.length - 1);
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();
}
}
5.實(shí)現(xiàn)加載更多的功能墅拭,效果范例107,后端在本地使用server-mock來模擬數(shù)據(jù)
GitHub
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者