題目1: ajax 是什么?有什么作用?
AJAX即“Asynchronous Javascript And XML”(異步JavaScript和XML)是一種在無需重新加載整個網(wǎng)頁的情況下,能夠更新部分網(wǎng)頁的技術(shù),它的作用就是在不重新加載頁面的情況下,向服務(wù)器請求數(shù)據(jù)并獲取服務(wù)器返回的內(nèi)容.
題目2: 前后端開發(fā)聯(lián)調(diào)需要注意哪些事情?后端接口完成前如何 mock 數(shù)據(jù)?
-
聯(lián)調(diào)注意:
約定好頁面需要的數(shù)據(jù)和數(shù)據(jù)類型
約定接口名稱
約定請求參數(shù)
約定相應(yīng)格式,例如成功返回什么消息,失敗返回什么消息 - ** 后端接口完成前如何 mock 數(shù)據(jù):**
使用 sever-mock 等工具搭建環(huán)境
題目3:點擊按鈕,使用 ajax 獲取數(shù)據(jù),如何在數(shù)據(jù)到來之前防止重復(fù)點擊?
var isLock = false
var curIndex = 3
var len = 5
btn.addEventListener('click',function (e) {
e.preventDefault()
if (isLock){
return
}
ajax('/loadmore',
{idx: curIndex, len: len},
function (data) {
appendData(data)
isLock = false
curIndex = curIndex + len
console.log(curIndex)
})
isLock = true
})
設(shè)置一個狀態(tài)鎖isLock,初始值為false,當(dāng)為true時,說明正在請求數(shù)據(jù),什么都不做,返回.當(dāng)為fals時,說明請求已經(jīng)來到,可以進(jìn)行下一次點擊了
題目4:封裝一個 ajax 函數(shù),能通過如下方式調(diào)用.后端在本地使用server-mock來 mock 數(shù)據(jù)
function ajax(opts){//todo...}
document.querySelector('#btn').addEventListener('click', function(){
ajax({ url: '/login', //接口地址
type: 'get', // 類型,post 或者 get,
data: { username: 'xiaoming', password: 'abcd1234' },
success: function(ret){ console.log(ret); // {status: 0} },
error: function(){ console.log('出錯了') }
})
});
function ajax(opts) {
var xhr = XMLHttpRequest();
var data = '';
for (vl in opts.data) {
data += vl + '=' + opts.data[vl] + '&';
}
data = data.substring(0, data.length - 1);
xhr.onreadystatechange = function() {
if (readyState == 200 && status == 4) {
opts.success(xhr.responseText);
}
if (xhr.redyState === 4 && xhr.status === 404) {
opts.error();
}
}
if (opts.type.toUpperCase() === 'GET') { //判斷使用哪種方式請求
xhr.open('GET', opts.url + '?' + data, true);
xhr.send();
}
if (opts.type.toUpperCase() === 'POST') {
xhr.open('POST', opts.url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
}
}
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('出錯了')
}
})
});