进阶12-ajax

2017-10-13  本文已影响0人  饥人谷_星璇

题目1: ajax 是什么?有什么作用?

题目2: 前后端开发联调需要注意哪些事情?后端接口完成前如何 mock 数据?

题目3:点击按钮,使用 ajax 获取数据,如何在数据到来之前防止重复点击?

题目4:实现加载更多的功能,效果范例,后端在本地使用server-mock来模拟数据

<!DOCTYPE html>
<html>
<head>
    <title>ajax</title>
<style type="text/css">
li {
    list-style: none;
    height:40px;
    line-height:40px;
    font-size: 18px;
    border:1px solid pink;
    border-radius: 3px;
    margin:5px;
}
a { 
    width:100px;
    height:40px;
    line-height:40px;
    font-size: 16px;
    border:1px solid pink;
    border-radius: 3px;
    margin:0 auto;
    display: block;
    text-align: center;
    text-decoration: none;
    color:pink;
}
</style>
</head>
<body>
<ul  id="ct">
</ul>
 <a href="#" class="btn" id="loadmore" >加载更多</a>
<script>
    var btn = document.querySelector(".btn");
    var loadmore = document.querySelector("#loadmore")
    var ct = document.querySelector("#ct")
    var index = 0;
    var judgeData = true; //点击之后数据到来之前设置judgeDate为false,防止重复点击
    btn.addEventListener("click",function(e){
        if(!judgeData){
            return;
        }
        judgeData = false;
        e.preventDefault();
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 ){
                if(xhr.status ===200||xhr.status ===304){
                    var results = JSON.parse(xhr.responseText)
                    var fragments = document.createDocumentFragment()
                    for(let i = 0;i < 5; i++){
                        var node = document.createElement("li")
                        node.innerText = results[i]
                        fragments.appendChild(node);
                    }
                ct.appendChild(fragments)
                index += 5;
                }else{
                    console.log("出错了")
                }
                judgeData = true;
            }
        }
        xhr.open("get","/loadMore?index=" + index + "&length=5" ,true)
        xhr.send();
    })
</script>
</body>
</html>
function setRouter(app){ 
 var router = app; 

//服务端router.js
app.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))
    }
    res.send(data)
});}
 module.exports.setRouter = setRouter
上一篇下一篇

猜你喜欢

热点阅读