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

时间:2011-05-09 18:56:45

标签: javascript jquery html ajax logging

我正在尝试制作一个几乎实时显示控制台输出的页面,我尝试了很多东西,但它们似乎都没有用,这是我的最新代码。

<!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 ---- undefined'。

谢谢!  贾斯汀

2 个答案:

答案 0 :(得分:1)

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>

答案 1 :(得分:0)

我认为你错过了初始化ohtml变量,并且javascript为它指定了undefined,所以你得到了上面提到的输出

相关问题