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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵