【发布时间】:2013-08-27 23:58:55
【问题描述】:
我一直在使用 Jquery .load 函数从 php 文件中请求元素并将其显示在页面上。起初,我只请求 first.php 中的元素,并且所有内容都在加载时完美加载。然后我创建了第二个函数来从 second.php 请求元素,这会导致 first.php 中的元素有时不加载(first.php 应该始终显示元素),而 second.php 每次都加载。出于某种原因,先加载 first.php,然后再返回到该文件使其再次正确加载。
attempts = 0;
$(document).ready(function(){
roll_info();
past_rolls();
});
function roll_info(){
$("#info").load("first.php", timer);
//to see how many times the function is called
attempts++;
});
}
function past_rolls(){
$("#prevRolls").load("second.php");
}
//called after roll_info()
function timer(){
//If the element requested by the ajax isn't added to the page it attempts to add again
if (!document.getElementById("roll_info"))
{
roll_info();
}
//Refreshes roll_info() every 10 seconds if loaded successfully until no longer waiting
else if (document.getElementById("status").innerHTML == "Status: Waiting..."){
nextRefresh = setInterval(function(){
roll_info();
clearInterval(nextRefresh);
return;},10000);
}
//other code
在控制台中查看“attempts”的值在加载后立即显示数字 1000+,这意味着它通过 ajax 发出了数千个失败的请求?控制台中也没有可见的错误。
知道是什么导致了这种不一致吗?
【问题讨论】:
-
你为什么将
$(document).ready()包装在另一个函数中?你应该只有一个$(document).ready()函数,它应该包装引用 DOM 元素的 jQuery 代码,以及你何时/如何调用page_load()? -
你能解释一下这个检查是针对
if (!document.getElementById("roll_info"))的吗? -
@koala_dev 我修复了 document.ready() 问题(第一天使用 jquery 大声笑) - 希望这就是问题所在。 if (!document.getElementById("roll_info")) 检查 first.php 中的元素是否已添加到页面中。如果不是,它会继续调用 roll_info 直到它工作(一旦它没有加载就永远不会)。
-
所以你想检查 load() 调用何时完成?如果是这样,那么设置一个回调函数,检查
load()的文档你不应该启动多个请求