JQuery加载(url)最初不工作,间隔后激活

JQuery load(url) not working initially, activates after interval

本文关键字:工作 激活 加载 url JQuery      更新时间:2023-09-26

我正试图使一个页面得到的Jquery加载到一个div。而且应该偶尔刷新一下。

现在刷新工作了。然而,初始页面加载没有。

我已经尽力确保我写了正确的代码。谁能给我指个正确的方向吗?

我的代码:

  <script type="text/javascript">
      jQuery(document).ready(function() {

                    $.ajaxSetup({
                        cache: false
                    }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
                    setInterval(function() {
                        $('#WebsiteImages').load('/images/?SetAjaxCall=loadimages');
                    }, 2000); // the "3000" here refers to the time to refresh the div. it is in milliseconds.
                    /// **** DEFAULT LOADING
                    //$('#WebsiteImages').html('Some set text :-)');
                    $('#WebsiteImages').load('/images/?SetAjaxCall=loadimages');
      });
   </script>

div:

<div id="WebsiteImages"></div>

奇怪的是,当取消注释:

$('#WebsiteImages').html('Some set text :-)');

That DOES work.

编辑我尝试了以下代码:

结果是一样的。(*尝试设置警报作为测试和代码运行,->我得到警报,所以没有解析错误*)

$(window).load(function() {     
    $('#WebsiteImages').load('images/?SetAjaxCall=loadimages');          
});

我也试图使一个函数加载后的页面加载:

function LoadImagePage(){
                            $('#WebsiteImages').load(''/images/?SetAjaxCall=loadimages');
                        }

还添加了一个警报来检查它是否已加载。它跑起来了。然而无济于事。

lshettyl下面的代码工作了!!

$(function() {
    $.ajaxSetup({
        cache: false
    });
    //IIFE
    (function loadStuff() {
        $('#WebsiteImages').load('/images/?SetAjaxCall=loadimages', function() {
            setTimeout(loadStuff, 2000);
        });
    }());
});

正如我在评论中所说,使用IIFE而不是重复代码会更清晰。我还建议在负载回调中使用setTimeout,而不是setInterval。下面是我所说的一个例子。请记住,您已经拥有的代码应该可以工作,除非在第一次调用中出现严重延迟,并且setInterval已经启动。

$(function() {
    $.ajaxSetup({
        cache: false
    });
    //IIFE
    (function loadStuff() {
        $('#WebsiteImages').load('/images/?SetAjaxCall=loadimages', function() {
            setTimeout(loadStuff, 2000);
        });
    }());
});

下面是的一个演示