1: ajax 是什么梁钾?有什么作用逊抡?
ajax是異步的js和XML(Async JavaScript And XML)冒嫡,是一種技術(shù)泛稱
可以異步傳遞數(shù)據(jù)和獲取數(shù)據(jù)孝凌,這就使ajax可以在不加載整個(gè)頁面的情況下對(duì)頁面局部更新,使用戶體驗(yàn)更佳瓣赂。
2: 前后端開發(fā)聯(lián)調(diào)需要注意哪些事情?后端接口完成前如何 mock 數(shù)據(jù)寨躁?
- get還是post方法
- 約定數(shù)據(jù)接口和格式牙勘,前端提供參數(shù)方面,后臺(tái)響應(yīng)時(shí)返回什么格式
- 約定每次請(qǐng)求數(shù)據(jù)數(shù)量
如何mock數(shù)據(jù)?
使用server mock搭建本地服務(wù)器操禀,模擬網(wǎng)站后端颓屑,使用server-mock首先得下載nodejs揪惦,然后下載server-mock(npm install -g server-mock)器腋,下載完成后,在目標(biāo)文件文件夾創(chuàng)建一個(gè)router.js文件夾纫塌,用來接收和處理后端的請(qǐng)求文件(mock init可創(chuàng)建范例)措左;最后mock start啟動(dòng)一個(gè)web服務(wù)器
3:點(diǎn)擊按鈕怎披,使用 ajax 獲取數(shù)據(jù)钳枕,如何在數(shù)據(jù)到來之前防止重復(fù)點(diǎn)擊?
var isDataArrive = true //設(shè)置一個(gè)狀態(tài)鎖初始為true
btn.addEventListener('click', function(e){
e.preventDefault()
if (!isDataArrive) {
return //數(shù)據(jù)沒到來時(shí)為true
}
if(xhr.readyState === 4){
if (xhr.status === 200 || xhr.status === 304) {
// dosomething
}
isDataArrive = true //數(shù)據(jù)到來后變?yōu)閠rue
}
}
xhr.open('get', '/loadmore?index='+ pageIndex +'&length=5', true)
xhr.send()
isDataArrive = false //發(fā)送數(shù)據(jù)之后數(shù)據(jù)到來前點(diǎn)擊沒用
})
4:實(shí)現(xiàn)加載更多的功能,后端在本地使用server-mock來模擬數(shù)據(jù)
<style type="text/css">
.ct li {
list-style: none;
border:1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
.btn {
display: block;
width: 80px;
height: 40px;
line-height: 40px;
border:1px solid;
border-radius: 4px;
text-align: center;
text-decoration: none;
margin:0 auto;
}
.btn:hover {
background: red;
color: #fff;
}
</style>
<body>
<ul class="ct">
</ul>
<a href="#" id="load-more" class="btn">加載更多</a>
<script>
var btn = document.querySelector('.btn')
var ct = document.querySelector('.ct')
var pageIndex = 0
var isDataArrive = true
btn.addEventListener('click', function(e){
e.preventDefault()
if (!isDataArrive) {
return
}
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if (xhr.status === 200 || xhr.status === 304) {
var result = JSON.parse(xhr.responseText)
console.log(result)
var fragment = document.createDocumentFragment()
for(var i = 0;i < result.length;i++){
var node = document.createElement('li')
node.innerText = result[i]
fragment.appendChild(node)
}
ct.appendChild(fragment)
pageIndex = pageIndex +5
}else {
alert('出錯(cuò)了')
}
isDataArrive = true
}
}
xhr.open('get', '/loadmore?index='+ pageIndex +'&length=5', true)
xhr.send()
isDataArrive = false
})
</script>
//后端
router.get('/loadmore',function(req,res){
var curIdx = req.query.index
var len = req.query.length
var data = []
for (var i = 0; i < len; i++) {
data.push('新聞' + (parseInt(curIdx) + i ))
}
setTimeout(function(){
res.send(data)
},5000)
})
//模擬慢網(wǎng)速