題目1: ajax 是什么?有什么作用?
AJAX即“Asynchronous Javascript And XML”(異步JavaScript和XML),是一種在無(wú)需重新加載整個(gè)網(wǎng)頁(yè)的情況下,能夠更新部分網(wǎng)頁(yè)的技術(shù),它的作用就是在不重新加載頁(yè)面的情況下,向服務(wù)器請(qǐng)求數(shù)據(jù)并獲取服務(wù)器返回的內(nèi)容。-
題目2: 前后端開發(fā)聯(lián)調(diào)需要注意哪些事情?后端接口完成前如何 mock 數(shù)據(jù)?
- 聯(lián)調(diào)注意:
- 約定好頁(yè)面需要的數(shù)據(jù)和數(shù)據(jù)類型
- 約定接口名稱
- 約定請(qǐng)求參數(shù)
- 約定相應(yīng)格式,例如成功返回什么消息,失敗返回什么消息
- 后端接口完成前如何 mock 數(shù)據(jù):
- 使用 sever-mock 等工具搭建環(huán)境
- 聯(lián)調(diào)注意:
-
題目3:點(diǎn)擊按鈕,使用 ajax 獲取數(shù)據(jù),如何在數(shù)據(jù)到來(lái)之前防止重復(fù)點(diǎn)擊?
//使用變量鎖定 var lock = false; btn.addEventListener('click', function() { if (!lock) { lock = true; ajax(XXXX); lock = false; } }); 題目4:封裝一個(gè) ajax 函數(shù),能通過(guò)如下方式調(diào)用。后端在本地使用server-mock來(lái) mock 數(shù)據(jù)
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') { //判斷使用哪種方式請(qǐng)求
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('出錯(cuò)了')
}
})
});
