【问题标题】:Run AJAX every x seconds with different data each time [closed]每x秒运行一次AJAX,每次使用不同的数据[关闭]
【发布时间】:2022-01-12 09:04:39
【问题描述】:

下面的代码每 5 秒执行一次。但是我想每次都返回不同的数据。

例如:

First interval = top level data (level.php)
Second interval = top skill data (skill.php)
Third interval = top magic data (magic.php)

一旦第三个间隔完成...返回 level.php 再次开始序列

有人能告诉我如何修改代码来实现我想要的吗?

<script>
    var text = "";
    var toplevel = function() {
        $.ajax({
            type : 'GET',
            url : '/pages/level.php',
            success : function(data){
            text = data;
            $("#tops").fadeOut( "normal", function() {
                $('#tops').html(data);
                $("#tops").fadeIn( "normal", function() {});
                });
            },
        });
    };

    $(document).ready(function(){
        setInterval(toplevel, 5000);
        toplevel();
    });
</script>

【问题讨论】:

  • 到目前为止,您尝试了哪些方法来自行解决此问题?真正的问题是什么?

标签: javascript jquery ajax


【解决方案1】:

您可以有一个 URL 数组,始终将请求发送到第一个,并在成功时轮换数组顺序:

function toplevel(urls) {
    return function () {
        $.get(urls[0]).done(function (data) {
            urls.push(urls.shift());
            $("#tops").fadeOut("normal", function () {
                $('#tops').html(data).fadeIn( "normal");
            });
        });
    }
};

$(function () {
    var switcher = toplevel(['/pages/level.php', '/pages/skill.php', '/pages/magic.php']);
    setInterval(switcher, 5000);
    switcher();
});

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 2019-03-09
    • 2016-07-24
    • 1970-01-01
    • 2012-07-11
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    相关资源
    最近更新 更多