題目1: ajax 是什么?有什么作用?
AJAX即Asynchronous JavaScript and XML,異步的 JavaScript 和 XML 通過(guò)在后臺(tái)與服務(wù)器進(jìn)行少量數(shù)據(jù)交換。
AJAX 可以使網(wǎng)頁(yè)實(shí)現(xiàn)異步更新。這意味著可以在不重新加載整個(gè)網(wǎng)頁(yè)的情況下,對(duì)網(wǎng)頁(yè)的某部分進(jìn)行更新。
題目2: 前后端開(kāi)發(fā)聯(lián)調(diào)需要注意哪些事情?后端接口完成前如何 mock 數(shù)據(jù)?
注意事項(xiàng):
- 約定數(shù)據(jù):有哪些需要傳輸?shù)臄?shù)據(jù),數(shù)據(jù)類型是什么;
- 約定接口:確定接口名稱及請(qǐng)求和響應(yīng)的格式,請(qǐng)求的參數(shù)名稱、響應(yīng)的數(shù)據(jù)格式。
mock數(shù)據(jù):
- 可以使用服務(wù)器框架搭建一個(gè)模擬服務(wù)器環(huán)境,比如使用express&nodejs或者使用xampp,更簡(jiǎn)單的辦法是使用server-mock。在數(shù)據(jù)的模擬傳輸與請(qǐng)求查看上,postman也是一個(gè)好工具。
題目3:點(diǎn)擊按鈕,使用 ajax 獲取數(shù)據(jù),如何在數(shù)據(jù)到來(lái)之前防止重復(fù)點(diǎn)擊?
使用狀態(tài)鎖來(lái)防止重復(fù)點(diǎn)擊。
//設(shè)置狀態(tài)鎖初始狀態(tài)
var ajaxIsLock = false;
function ajax(){
//檢查狀態(tài)鎖
if(ajaxIsLock){
return;
}
ajaxIsLock = true; //上鎖
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200 || xhr.status === 304){
ajaxIsLock = false //解鎖
}
}
}
題目4:封裝一個(gè) ajax 函數(shù),能通過(guò)如下方式調(diào)用。后端在本地使用server-mock來(lái) mock 數(shù)據(jù)
function ajax(opts){
opts.type = opts.type || 'GET';
opts.success = opts.success || function(){};
opts.error = opts.error || function(){};
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 xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 304) {
if (opts.dataType === 'text') {
opts.success(xhr.responseText);
} else if (opts.dataType === 'json') {
var json = JSON.parse(xhr.responseText);
opts.success(json);
}
} else {
opts.error();
}
}
}
if (opts.type.toLowerCase() === "get") {
xhr.open("get", opts.url + "?" + dataStr, true);
xhr.send();
} else if (opts.type.toLowerCase() === "post") {
xhr.open("post", opts.url, true);
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(dataStr);
}
}
document.querySelector('#btn').addEventListener('click', function(){
ajax({
url: '/login', //接口地址
type: 'get', // 類型, post 或者 get,
data: {
username: 'xiaoming',
password: 'abcd1234'
},
dataType: 'text',
success: function(ret){
alert(ret); // {status: 0}
},
error: function(){
console.log('出錯(cuò)了')
}
})
});