【问题标题】:Ajax only display on page update not functioning?Ajax 仅显示在页面更新不起作用?
【发布时间】:2011-08-21 22:07:11
【问题描述】:

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

<!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”。

谢谢! 贾斯汀

【问题讨论】:

  • 代码中的ohtml在哪里定义?

标签: javascript jquery html ajax logging


【解决方案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>

【讨论】:

    【解决方案2】:

    我认为你错过了初始化 ohtml 变量,并且 javascript 将 undefined 分配给它,所以你得到了提到的输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 2012-08-21
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      相关资源
      最近更新 更多