2011-05-09 101 views
0

我試圖做一個頁面,顯示近乎實時的控制檯輸出,我已經嘗試了很多東西,但沒有一個似乎工作,這裏是我最新的代碼。Ajax只顯示頁面更新無法正常工作?

<!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請求的頁面,並將其添加到每一個點擊時的股利,即使它在同一行。我只想顯示新行​​而不是重複。

運行時,alert()輸出'HTMLHTMLHTMLHTML ---- undefined'。

謝謝! 賈斯汀

+0

ohtml在代碼中定義的位置? – 2011-05-09 19:14:42

回答

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> 
+0

工作!謝謝! – Justin 2011-05-10 13:39:53

0

我想你已經錯過了初始化變量ohtml和JavaScript分配未定義它,因此你所得到的輸出提到

+0

它仍然... – Justin 2011-05-09 19:21:31