JQuery 最大 .load 调用



我正在使用LiquidSlider框架,每个选项卡中都有很多HTML。所以我决定将HTML放入单独的.html文件中,以使主页index.html更干净。

这是我的 HTML:

..
<head>
    .. <-- Import jquery, slider files, etc -->
    <!-- Import HTML from other files into divs -->
    <script>
      $(function(){
        $("#about-content").load("about.html");
        $("#other-content").load("other.html");
        $("#help-content").load("help.html");
        $("#contact-content").load("contact.html");
      });
  </script> 
</head>
<body>
  <section id="navigation">
    ..
  </section>
  <div class="liquid-slider" id="main-slider">
    <!-- About -->
    <div>
      <h2 class="title">about</h2>
      <div id="about-content"></div>
    </div>
    <!-- Other -->
    <div>
      <h2 class="title">other</h2>
      <div id="other-content"></div>
    </div>
    <!-- Help -->
    <div>
      <h2 class="title">help</h2>
      <div id="help-content"></div>
    </div>
    <!-- Contact -->
    <div>
      <h2 class="title">contact</h2>
      <div id="contact-content"></div>
    </div>
  </div>
  <section id="footer">
    ..
  </section>
</body>
..

因此,当文档加载时,理论上HTML将通过.load调用加载,对吗?它似乎工作正常,直到它到达最后一个选项卡(contact),在那里它无法加载任何内容。

奇怪吧?我尝试移动divs以查看是否是我的html文件出现问题,但最后一个元素总是无法加载。然后我尝试添加另一个选项卡,最后两个无法加载。这让我相信.load呼叫的数量是有上限的,上限为 3?

有人有任何想法或看到任何明显的问题吗?甚至提出更好的方法来实现同样的事情?

谢谢。

RTM,没有关于最大调用次数的信息,但是有很多关于您可以使用哪种回调的信息(和示例),这可能只是帮助您诊断问题本身,例如:

$("#contact-content").load("contact.html", function( response, status, xhr )
{
    if ( status == "error" )
    {
        var msg = "Sorry but there was an error: ";
        console.log(xhr);//<-- check this
        $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
    }
});

作为替代方案,只需进行老式的$.get调用,因为您似乎没有将任何数据传递给服务器:

$.get( "contact.html", function( data )
{
    $("#contact-content").html(data);
});

另一件需要考虑的事情可能是:鉴于您使用的是liquidSlider,我认为并非所有内容都可以看到。为什么不注册一个点击处理程序,当用户实际点击某些内容时,.load该内容?这消除了那一系列的加载调用...也许这是某种并发问题。我的意思是:浏览器限制了可以发出的并发 AJAX 请求的数量。也许您遇到了该限制,并且必须等待请求完成?这是一个很长的镜头,但你永远不知道...如果您愿意,请在此处检查您的浏览器

但无论哪种方式,使用 JS 动态获取部分内容都很好,但请记住,我可以在浏览器中关闭 JS 支持。或者,如果你的JS包含语法错误,脚本执行就会停止,给我留下一个(半)空白页来凝视。
在我看来,仅使用任何服务器端脚本语言似乎更适合:

//index.php -- using PHP as an example
<div id="contact-content"><?php include 'contact.html'; ?></div>

在PHP处理之后,来自服务器的响应将是一个成熟的html页面,不需要任何JS-on-the-Speed加载。它几乎肯定会表现得更好,并且仍然允许在你的服务器上使用更干净的 html 代码......

在我看来,

服务器端包含似乎是实现相同目标的更好方法。 使用正确的工具完成正确的工作等等。

<script>
var array = ['about', 'other', 'contact', 'help'];
for (i in array)                               
    {
    $('#'+array[i]).load(array[i]+'.html', function(){ });
    }
</script>

最新更新