我一直在使用 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 发出了数千次失败的请求?控制台中也没有可见的错误。
知道是什么导致了这种不一致吗?
最佳答案
如果您想知道何时加载first.php 或second.php,请提供回调函数.load
。 .
示例来自 jQuery api网站:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
只需将 ajax/test.html 替换为 first/second.php。
顺便说一句,您不应该使用 setInterval 来检查文件是否已加载。
关于php - Jquery/Ajax .load() 随机不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18477307/