简体   繁体   中英

Ajax only display on page update not functioning?

I'm trying to make a page that displays console output in near real-time, I have tried many things but none of them seem to work, here is my latest code.

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

The file 'read.php' outputs the last line of the console log, Ajax requests the page and adds it to the div every time it's clicked, even though it's the same line. I would like to only display new lines and not duplicates.

When ran, the alert() outputs 'HTMLHTMLHTMLHTML ---- undefined'.

Thanks! Justin

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

So you need to make it work in scope

<!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为它分配了undefined,因此您得到的是上述输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM