2013-08-01 41 views
0

我編寫了這段代碼從數據庫中獲取新數據,但是我不知道這段代碼有什麼問題,以及爲什麼我在瀏覽器控制檯中收到以下錯誤。修復了jQuery setInterval和JSON

jQuery代碼:

$(document).ready(function() { 
    setInterval(function() { 
     var lastdate = $("#countcomment").attr("loadtime"); 
     $.post("update.php",{ajax:"1", lastdate:lastdate},function(data){ 
      if(data.getnew){ 
       $('#countcomment').html(data.getnew); 
       $('#countcomment').attr('loadtime', ""+data.new) 
      } 
     }, "json"); 
    }, 1000); 
}); 

PHP:

$database = $db->super_query(" 
    SELECT count(*) as count 
    FROM ".PREFIX."_comments 
    WHERE date >= '$real_date' 
"); 

$newcomments = $database['count']; 

if($newcomments > "0"){ 
    echo "{\"getnew\":\"{$newcomments}\",\"new\":\"{$now_date}\"}"; 
} 

HTML:

<span id="countcomment" loadtime="2013"></span> 

的錯誤:

Uncaught TypeError: Cannot read property 'getnew' of null 

我不知道是什麼問題!

+2

應首先驗證數據正在返回正確throught控制檯,控制檯.LOG(數據); – Rooster

+0

我不知道這是否會解決您的問題,但您可能想嘗試'$ response = array('getnew'=> $ newcomments,'new'=> $ now_date); echo json_encode($ response);' – kalley

+0

@kalley,不工作 – Alireza

回答

1

可能是您的服務器發送的數據比您預期的要多(例如錯誤)。 使用下面的js代碼檢查響應數據:

$(document).ready(function() { 
    setInterval(function() { 
    var lastdate = $("#countcomment").attr("loadtime"); 
    $.post("update.php",{ajax:"1", lastdate:lastdate},function(data, status, xhr){ 
    console.log(xhr.responseText) 
    },"json"); 
    }, 1000); 
}); 

或者,你可以看到在Chrome的開發者工具中的「網絡」選項卡中的數據

+0

謝謝我的朋友,問題出現在PHP文件中... – Alireza