ajax 是什么?有什么作用震嫉?
ajax通過原生的XMLHttpRequest對象發(fā)出HTTP請求森瘪,得到服務器返回的數(shù)據(jù)后,再進行處理票堵。
ajax可以無需刷新整個網(wǎng)頁扼睬,而是對部分網(wǎng)頁進行刷新。
前后端開發(fā)聯(lián)調(diào)需要注意哪些事情悴势?后端接口完成前如何 mock 數(shù)據(jù)痰驱?
前后端進行開發(fā)前,要定義好接口以及數(shù)據(jù)形式等細節(jié)瞳浦,已達到解耦效果。
后端接口完成前废士,前端可以通過MOCKJS等工具模擬數(shù)據(jù)叫潦。
點擊按鈕,使用 ajax 獲取數(shù)據(jù)官硝,如何在數(shù)據(jù)到來之前防止重復點擊?
通過設定標記
var flag=false;
tn.addEventListener('click', function(e) {
//......
flag = true;
if(flag){
return;
}
});
在請求數(shù)據(jù)時矗蕊,函數(shù)flag設為false,保證不重復點擊
代碼
- 封裝一個 ajax 函數(shù),能通過如下方式調(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('出錯了')
}
})
});
實現(xiàn):
function ajax(opts){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var ret = JSON.parse(xmlhttp.responseText);
opts.success(ret);
}
if(xmlhttp.status == 404){
opts.error();
}
};
var dataStr = '';
for(var key in opts.data){
dataStr += key + '=' + opts.data[key] + '&';
}
dataStr = dataStr.substr(0,dataStr.length-1);
if(opts.type.toLowerCase() == 'post'){
xmlhttp.open(opts.type,opts.url,true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(dataStr);
}
if(opts.type.toLowerCase() == 'get'){
xmlhttp.open(opts.type,opts.url+'?'+dataStr,true);
xmlhttp.send();
}
}
- 實現(xiàn)如下加載更多的功能傻咖。效果如下: http://jrgzuoye.applinzi.com/作業(yè)安排/jscode/JS9-jqueryajax/1.html
新浪云
源碼 - 實現(xiàn)注冊表單驗證功能效果如下:http://jrgzuoye.applinzi.com/作業(yè)安排/jscode/JS7-ajax/3.html
新浪云
源碼