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 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥50 用logisim设计16位单时钟周期cpu
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据
  • ¥15 请上面代码做什么处理或什么混淆
  • ¥15 英雄联盟自定义房间置顶
  • ¥15 W5500网线插上无反应
  • ¥15 如何用字典的Key,显示在WPF的xaml中
  • ¥15 weautomate读取Excel表格信息然后填写到网页一直报错,如何解决?
  • ¥15 C#如何在Webview2中获取网页验证码