Ajax 仅在页面更新时显示不起作用

Ajax only display on page update not functioning?

本文关键字:显示 不起作用 更新 Ajax      更新时间:2023-09-26

我正在尝试制作一个近乎实时显示控制台输出的页面,我已经尝试了很多方法,但似乎都没有工作,这是我的最新代码。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<html> 
<head> 
<title>CP</title> 
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function update() {
    $.ajax({
        url: "read.php",
        cache: false,
        success: function(html){            
            if(html == ohtml) {
                alert(html+" ---- "+ohtml);
            } else {
                alert(html+" ---- "+ohtml);
                var ohtml = html;
                $("#consoleOP").append(html+"<br />");  
            }
        }
    });
}
</script>
</head> 
<body> 
   <div style='width: 800px; margin-left: auto; margin-right: auto;'><p>
   <input type="button" value="Refresh" onclick="update()" /></p> 
<div id="consoleOP"></div> 
</div>
</body> 
</html>

文件"read.php"输出控制台日志的最后一行,Ajax 请求该页面并在每次单击时将其添加到div 中,即使它是同一行。我只想显示新行而不是重复。

运行时,alert() 输出 'HTMLHTMLHTMLHTML ----未定义'。

谢谢! 贾斯汀

else {
            alert(html+" ---- "+ohtml);
            var ohtml = html;  <-- I am local and you are treating me as a global
            $("#consoleOP").append(html+"<br />");  
        }

所以你需要让它在范围内工作

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<html> 
<head> 
<title>CP</title> 
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">

jQuery(function(){
    var ohtml = null;
    function update() {
        $.ajax({
            url: "read.php",
            cache: false,
            success: function(html){            
                if(html == ohtml) {
                    alert(html+" ---- "+ohtml);
                } else {
                    alert(html+" ---- "+ohtml);
                    ohtml = html;
                    $("#consoleOP").append(html+"<br />");  
                }
            }
        });
    }
    jQuery("#btnRefresh").click( update );
});
</script>
</head> 
<body> 
   <div style='width: 800px; margin-left: auto; margin-right: auto;'><p>
   <input type="button" id="btnRefresh" value="Refresh" /></p> 
<div id="consoleOP"></div> 
</div>
</body> 
</html>

我认为您错过了初始化 ohtml 变量,并且 javascript 为其分配了未定义,因此您获得了提到的输出