AJAX 加載更多(加數(shù)據(jù)鎖)

jsbin展示

  • 有時(shí)候網(wǎng)絡(luò)延時(shí),用戶多次點(diǎn)擊按鈕發(fā)送請(qǐng)求,后端接收到多個(gè)重復(fù)的請(qǐng)求,浪費(fèi)流量。
  • 在前端加個(gè)數(shù)據(jù)鎖就能解決這個(gè)問(wèn)題。
  • 下面是對(duì)封裝的ajax加數(shù)據(jù)鎖的例子

前端html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        ul,
        li {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        #news>li {
            width: 600px;
            border: 1px solid #000080;
            border-radius: 5px;
            font-size: 1.25rem;
            margin: 0 auto;
            text-align: center;
            padding: 5px;
            margin-top: 10px;
        }

        .btn {
            width: 200px;
            display: block;
            margin: 0 auto;
            margin-top: 20px;
            font-size: 1.5rem;
            padding: 10px;
            background: #AFEEEE;
        }
    </style>
</head>

<body>
    <ul id="news">
        <li>新聞1</li>
        <li>新聞2</li>
        <li>新聞3</li>
        <li>新聞4</li>
        <li>新聞5</li>
    </ul>
    <button id="more" class="btn">加載更多</button>
</body>
<script>
    var btn = $("#more");
    var newsList = $("#news");
    var dataLock = true;   // 數(shù)據(jù)鎖初始是打開(kāi)的

    btn.addEventListener("click", function() {
        if (!dataLock) {
            return
        }                  // 查看數(shù)據(jù)鎖是否關(guān)閉,如果關(guān)閉就退出函數(shù)
        dataLock = false;
        ajax({
            type: "get",   //可以改為post請(qǐng)求哦!
            url: "/loadMore",
            data: {
                index: newsList.children.length,
                needPage: 3
            },
            success: function (callback){
                addNews(callback);
                dataLock = true;    // 后端發(fā)回?cái)?shù)據(jù)后,打開(kāi)數(shù)據(jù)鎖

            },
            error: function() {
                console.log("出錯(cuò)了")
            }
        })
    })

    function addNews(arr) {
        var frag = document.createDocumentFragment();
        for (var i = 0; i < arr.length; i++) {
            var list = document.createElement("li");
            list.innerText = arr[i];
            frag.appendChild(list);
        }
        news.appendChild(frag)
    }

    function ajax(opt) {
        var xhr = new XMLHttpRequest();
        //  /loadMore?index=5&needPage=3&
        var url = "";
        for (var key in opt.data) {
            url += key + "=" + opt.data[key] + "&";
        }

        console.log("url:", url)

        if (opt.type === "post") {
            xhr.open(opt.type, opt.url, true)
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
            setTimeout(function(){    // 模擬網(wǎng)絡(luò)延時(shí),2秒后發(fā)送請(qǐng)求
                xhr.send(url)
            }, 2000)

        }
        if (opt.type === "get") {
            xhr.open(opt.type, opt.url + "?" + url, true)
            setTimeout(function() {    // 模擬網(wǎng)絡(luò)延時(shí),2秒后發(fā)送請(qǐng)求
                xhr.send()
            }, 2000)

        }

        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {

                if (xhr.status === 200 || xhr.status === 304) {
                    var result = JSON.parse(xhr.responseText)
                    console.log(result)
                    opt.success(result)
                } else {
                    opt.error()
                }
            }
        }
    }

    function $(str) {
        return document.querySelector(str);
    }
</script>

</html>

app.get("/loadMore", function(req, res) {
    var idx = req.query.index;
    var ndpg = req.query.needPage;
    var news = [];
    for (var i = 0; i < ndpg; i++) {
        news.push("新聞get" + (parseInt(idx) + i + 1))
    }
    res.send(news)
})



app.post("/loadMore", function(req, res) {
        var idx = req.body.index;
        var ndpg = req.body.needPage;
        var news = [];
        for (var i = 0; i < ndpg; i++) {
            news.push("新聞post" + (parseInt(idx) + i + 1))
        }
        res.send(news)
        // setTimeout(function(){
        //     res.send(news)
        // }, 1000)
    })

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容