GET请求使用Window滚动触发两次

时间:2019-01-28 15:49:11

标签: jquery

当Window滚动事件的值为true时,我正在获取一些ajax。在“网络”选项卡中,我注意到每个事件都连续触发两次GET请求,即使我已设置超时标志来禁用多次运行ajax函数(当前为3秒)。

为什么会这样?

谢谢。

编辑:我刚注意到的一件事是,在准备就绪的文档中,它会触发两次,因此它甚至可能与滚动无关。

get request firing twice

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery Infinite Scroll</title>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">

    var offset = 0;
    var limit = 10;
    // jsonplaceholder is an working example endpoint.
    var apiEndpoint = "https://jsonplaceholder.typicode.com/posts?_offset=";
    var working = false;

    $(document).ready(function() {
        getContent();
    });

    $(window).scroll(function() {
        console.log("Fired if ==", $(window).scrollTop() + $(window).height(), getDocHeight());
        if ($(window).scrollTop() + $(window).height() == getDocHeight()) {
            if (working == false) {
                working = true;
                getContent();
                //console.log("Fired! Offest = ", offset);
            }
        }
    });

    function getContent() {
        $.ajax({
            type: "GET",
            url: apiEndpoint+offset+"&_limit="+limit,
            processData: false,
            contentType: "application/json",
            data: '',
            success: function(res) {
                //console.log(res);
                for (var i = 0; i < res.length; i++) {
                    // replace title and body with properties you need to extract from res
                    $('body').append("<div><h1>"+res[i].title+"</h1><p>Content: "+res[i].body+"</p></div>");
                }
                // no need to run timeout on first use (page load)
                if(offset !== 0){
                    // stop ajax call firing too rapidly 
                    setTimeout(function() {
                        working = false;
                    }, 3000)
                }
                offset += 5;
            },
            error: function(res) {
                console.log("Something went wrong! - ", res);
            }
        });
    }

    // Get document height (cross-browser compatibility)
    function getDocHeight() {
        var D = document;
        return Math.max(
            D.body.scrollHeight, D.documentElement.scrollHeight,
            D.body.offsetHeight, D.documentElement.offsetHeight,
            D.body.clientHeight, D.documentElement.clientHeight
        );
    }

    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

salam,您的get请求是第二个请求,在第一个请求中,方法类型为“ OPTIONS”表示对通信信息的请求

了解更多详情,DOC