TJ Crowder从这个问题中得到的代码(jQuery按顺序加载内容)是我的基础,但由于某种原因,它没有像我预期的那样工作。
我是如何阅读它的,它应该加载页面并有4个div,基本上显示:
面板1面板2面板3面板4
然后,它应该按顺序,一个接一个地从数据页属性加载URL,并将"Panel X"替换为它从该数据页的URL中提取的内容。
我将在一些需要一段时间才能加载的图表中使用它,所以我在我的网站上写了一个"测试"页面(test.php文件),它实际上等待5秒,然后显示一个随机数和一些伊索寓言,以模拟延迟,然后转储一些文本。
如果你转到测试文件,它工作得很好,但它不是从TJ的代码中加载的。我遗漏了什么吗?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div class="panel" data-page="http://jamesorr.com/test.php">Panel 1</div>
<div class="panel" data-page="http://jamesorr.com/test.php">Panel 2</div>
<div class="panel" data-page="http://jamesorr.com/test.php">Panel 3</div>
<div class="panel" data-page="http://jamesorr.com/test.php">Panel 4</div>
<script>
// Assumes script is at the bottom of the page, just before </body>
(function() {
var index = 0,
panels = $(".panel");
triggerLoad();
function triggerLoad() {
var panel;
if (index <= panels.length) {
panel = $(panels[index]);
++index;
panel.load(panel.attr("data-page"), triggerLoad);
}
}
})();
</script>
</body>
</html>
因此,根据下面的一些评论,我正在我自己的域上尝试WordPress插件,我将在其中使用它。
它似乎对我在那里也不起作用。
我想这可能是"test.php"文件的路径,所以我甚至尝试过测试几个位置,但它仍然不起作用:
$Content .= "<h2>Bigger Test</h2>'n'n";
$Content .= "<div class='"panel'" data-page='"test.php'">Panel 1</div>'n";
$Content .= "<div class='"panel'" data-page='"./test.php'">Panel 1</div>'n";
$Content .= "<div class='"panel'" data-page='"../test.php'">Panel 1</div>'n";
$Content .= "<div class='"panel'" data-page='"../../test.php'">Panel 1</div>'n";
$Content .= "<div class='"panel'" data-page='"../../../test.php'">Panel 1</div>'n";
$Content .= "<div class='"panel'" data-page='"../../../../test.php'">Panel 1</div>'n";
$Content .= "<div class='"panel'" data-page='"../../../../../test.php'">Panel 1</div>'n";
$Content .= "<h2>Part 2 of Bigger Test</h2>'n'n";
$Content .= "<div class='"panel'" data-page='"./test.php'">Panel 2</div>'n";
$Content .= "<h2>Part 3 of Bigger Test</h2>'n'n";
$Content .= "<div class='"panel'" data-page='"test.php'">Panel 3</div>'n";
$Content .= "<h2>Part 4 (Final) of Bigger Test</h2>'n'n";
$Content .= "<div class='"panel'" data-page='"http://jamesorr.com/wp-content/plugins/realestatedata/test.php'">Panel 4</div>'n";
$Content .= <<< EOT
<script>
// Assumes script is at the bottom of the page, just before </body>
(function() {
var index = 0,
panels = $(".panel");
triggerLoad();
function triggerLoad() {
var panel;
if (index <= panels.length) {
panel = $(panels[index]);
++index;
panel.load(panel.attr("data-page"), triggerLoad);
}
}
})();
</script>
EOT;
仍然没有在任何div中显示test.php输出文件的预期内容。
如果http://jamesorr.com/test.php
是跨域请求,则由于安全原因,jquery load
将无法工作。但如果是同源请求,它应该会起作用。优化您的代码,因为triggerLoad()
的执行次数超过了预期(5次而不是4次)。
if (index < panels.length) {
panel = $(panels[index]);
++index;
panel.load(panel.attr("data-page"), triggerLoad);
}