doujie1908 2016-12-20 00:06
浏览 50
已采纳

循环Ajax调用

I have a simple Ajax call and for some reason I am unable to get the call to refresh the data properly.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
    var myFunction = $(document).ready(function(){
      $("#div1").load("feeds.php");
    });
    setInterval(myFunction, 1000);
    </script>
  </head>
  <body>

  </body>
</html>

If I cut out of my attempt at an interval, It loads, but only once.

$(document).ready(function(){
  $("#div1").load("feeds.php");
});

Any ideas where I am going on? My understanding of Ajax is a work in progress.

Thanks!

  • 写回答

3条回答 默认 最新

  • dopmgo4707 2016-12-20 00:20
    关注

    $(document).ready(...) returns a jQuery object - so it can't be used as the argument to setInterval, which expects a function as it's first argument

    Your code needs to be written

    $(document).ready(function() {
        function myFunction(){
            $("#div1").load("feeds.php");
        }
        setInterval(myFunction, 1000);
    });
    

    or even

    function myFunction(){
        $("#div1").load("feeds.php");
    }
    $(document).ready(function() {
        setInterval(myFunction, 1000);
    });
    

    This way, myFunction is globally visible

    You also need to have an element with id=div1 for this code to work

    so: the whole thing looks like

    <!DOCTYPE html>
    <html>
      <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script>
            function myFunction(){
                $("#div1").load("feeds.php");
            }
            $(document).ready(function() {
                setInterval(myFunction, 1000);
            });
        </script>
      </head>
      <body>
        <div id="div1"></div>
      </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料