ajax 是什么誉察?有什么作用域帐?
- AJAX 在瀏覽器與 Web 服務(wù)器之間使用異步數(shù)據(jù)傳輸(HTTP 請(qǐng)求)從服務(wù)器獲取數(shù)據(jù).
通過(guò)JavaScript發(fā)送請(qǐng)求痒谴、接受服務(wù)器傳來(lái)的數(shù)據(jù)稚铣,然后操作DOM將新數(shù)據(jù)對(duì)網(wǎng)頁(yè)的某部分進(jìn)行更新箱叁,使用Ajax最直觀的感受是向服務(wù)器獲取新數(shù)據(jù)不需要刷新頁(yè)面等待
前后端開發(fā)聯(lián)調(diào)需要注意哪些事情墅垮?后端接口完成前如何 mock 數(shù)據(jù)?
- 前后端進(jìn)行開發(fā)前耕漱,注意接口的名字算色,請(qǐng)求的方式,數(shù)據(jù)的類型
- 后端接口完成前螟够,前端可以通過(guò)MOCKJS等工具模擬數(shù)據(jù)灾梦。
點(diǎn)擊按鈕,使用 ajax 獲取數(shù)據(jù)妓笙,如何在數(shù)據(jù)到來(lái)之前防止重復(fù)點(diǎn)擊?
- 可以設(shè)置狀態(tài)鎖
var flag=false;//設(shè)置狀態(tài)鎖
btn.addEventListerner('click',function(){
if(!flag){
flag=true;//打開狀態(tài)鎖
//to do運(yùn)行代碼
flag=false;//執(zhí)行完代碼若河,將狀態(tài)鎖關(guān)閉
}
}) - 使用計(jì)時(shí)器
var oBtn=document.querySelector(".button");
var clockTime=null;
oBtn.addEventListener("click",function(){
if(clockTime){
clearTimeout(clockTime)
}
clockTime=setTimeout(function(){
//to do
},5000)
})
封裝一個(gè) ajax 函數(shù),能通過(guò)如下方式調(diào)用
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('出錯(cuò)了')
}
})
});
代碼如下
function ajax(opts){
var xml = new XMLHttpRequest;
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
var jsonStr = JSON.parse(xml.responseText)
opts.success(jsonStr);
}
if(xml.status == 404){
opts.error()
}
}
var dataStr = '';
for(key in opts){
dataStr += key + '=' + opts.data[key] + "&";
};
dataStr= dataStr.substr(0,dataStr.length-1);
if(opts.type.toLowerCase == 'post'){
xml.open(post,opts.url,true);
xml.setreRequestHeader('Content-type','application-x-www-form-urlencoded');
xml.send(dataStr);
}
if(opts.type.toLowerCase == 'get'){
xml.open(get,opts.url+'?'+dataStr,true);
xml.send();
}
}