ajax是什么?有什么作用?
Ajax可以把它當(dāng)做頁(yè)面與后端交接的微橋梁,可以實(shí)現(xiàn)異步操作,無(wú)須刷新整個(gè)頁(yè)面的情況下實(shí)現(xiàn)局部刷新,是前端開發(fā)人員必須掌握的一個(gè)技能;
大體步驟可以分為以下:
1.createXHR
2.xhr.open(type,url,boolean) //確定請(qǐng)求發(fā)送類型、URL、同步/異步
3.xhr.send() //發(fā)送到服務(wù)器
前后端開發(fā)聯(lián)調(diào)需要注意哪些事情?后端接口完成前如何mock數(shù)據(jù)?
明確需要測(cè)試的數(shù)據(jù),邏輯測(cè)試需要清晰,前端發(fā)送什么數(shù)據(jù)給后臺(tái),后頭返回什么數(shù)據(jù)給前臺(tái),雙方約定好;后端接口完成前,搭建服務(wù)器,mock數(shù)據(jù),確定程序能跑起來(lái)。
點(diǎn)擊按鈕,使用 ajax 獲取數(shù)據(jù),如何在數(shù)據(jù)到來(lái)之前防止重復(fù)點(diǎn)擊?
<script>
var ct = document.querySelector("#ct");
btn = document.querySelector("#btn");
var lock = true;
function ajax(opts){
lock = false;
var xhr = new XMLHttpRequest();
xhr.onredaystatechange = function(){
if(xhr.readyState===4 && xhr.status===200){
var result = JSON.parse(xhr.responseText);
opts.success(xhr.responseText);
lock = true;
}else if(xhr.readyState===4 && xhr.status!==200) {
opts.error();
lock = true;
}
}
var urlStr ="";
for(var key in opts.data){
urlStr = key +"="+opts.data[key]+"$";
}
urlStr = urlStr.substring(0,urlStr.length-1);
if(opts.type.toLowerCase()==="get"){
xhr.open(opts.type,opts.url+"?"+urlStr,true);
xhr.send();
}
if(opts.type.toLowerCase()==="post"){
xhr.open(opts.type,opts.url,true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(urlStr)
}
}
btn.addEventListener("click",function(){
if(lock===true){
ajax(
{
url:'/more',
type: 'post',
data: {
len: document.querySelectorAll('li').length
},
success: function(data){
console.log(data);
},
error: function(){
console.log('出錯(cuò)了')
}
})
}
})
</script>