一、Ajax 是什么?有什么作用?
1.Ajax是Asynchronous JavaScript And XML的縮寫,這一技術能夠從服務器獲取額外的數據而無需刷新整個頁面,會帶來良好的用戶體驗;
2.Ajax在瀏覽器和Web服務器之間使用異步數據傳輸(HTTP請求)從服務器獲取數據;
3.Ajax本質就是用JS創造了一個XMLHttpRequest對象,這個對象可以操作瀏覽器的接口,不通過頁面刷新,而是直接向后臺發送請求獲取數據,然后瀏覽器進行展示改變網頁;
4.使用Ajax最直觀的感受就是向服務器獲取數據不需要刷新頁面等待了。
Ajax使用的四大步驟
二、前后端開發聯調需要注意哪些事情?后端接口完成前如何 mock 數據?(npm install -g server-mock)
1.需要注意的事情:
- 約定前后端聯調的時間。
- 約定雙方需要傳輸的數據和接口,在接口文檔中確定好參數的名稱、格式等。
- 約定請求和響應的格式和內容。
2.mock數據的方法有:
- 使用server-mock或mock.js搭建模擬服務器,進行模擬測試;
- 使用XAMPP等工具,編寫PHP文件來進行測試。
三、點擊按鈕,使用 ajax 獲取數據,如何在數據到來之前防止重復點擊?
var isLocked = false;//利用布爾值作為狀態鎖
btn.addEventListener('click',function(){
if(isLocked == true){
return;
}
isLocked = true;//先上鎖
ajax({
...
});
});
function success(){
...
isLocked = false;//解鎖
}
function erreo(){
...
isLocked = false;//解鎖
}
代碼練習
四、封裝一個 ajax 函數,能通過如下方式調用
function ajax(opts){
// todo ...
}
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('出錯了')
}
})
});
代碼:
function ajax(opts){
//創建ajax對象
var xmlhttp=new XMLHttpRequest();
//對ajax進行事件監聽
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState===4&&xmlhttp.status===200){
//將服務器返回的文本內容轉換為JSON格式
var json=JSON.parse(xmlhttp.responseText);
opts.success(json);
}
if(xmlhttp.status===404){
opts.error();
}
}
//創建發送到服務器的數據,為了讓數據附加到url上,必須為key/value格式
var dataStr="";
for(var key in opts.data){
dataStr+=key+"="+opts.data[key]+"&";
}
dataStr=dataStr.substr(0,dataStr.length-1);
//判斷請求的方式為GET
if(opts.type.toLowerCase()==="GET"){
//連接服務器
xmlhttp.open("GET",opts.url+"?"+dataStr,true);
//發送請求
xmlhttp.send();
}
//判斷請求方式為post
if(opts.type.toLowerCase()==="post"){
xmlhttp.open("POST",opts.url,true);
//為了使post請求與提交web表單相同,
//將Content-Type頭部信息設置為application/x-www-form-urlencoded來模仿表單提交功能
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send(dataStr);
}
}