php - Jquery/Ajax .load() 随机不工作?

标签 php jquery ajax

我一直在使用 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.phpsecond.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/

相关文章:

PHP 警告 : Unable to load dynamic library '/usr/lib64/php/modules/solr.so' undefined symbol: php_json_decode_ex in Unknown on line 0

jquery - Firefox 与 Chrome 中对 jquery.get 的不同响应

jquery - 让 Isotope 在 AJAX 加载的容器上工作

javascript - 使用 jQuery 检查数据库行是否存在

php - 带 CodeIgniter 的 Paypal IPN

php - 警告 : Module ini file doesn't exist under/etc/php/7. 0/模组可用

javascript - 是否可以向 eval(data); 添加回调?

javascript - GoJS 如何自上而下地排列调色板和图表中的节点

javascript - 列出jquery select的所有函数

javascript - jquery ajax inside .each 如何在整个.each完成时触发函数