2016-11-18 17 views
0

我想在後發現新的註釋,並添加一個通知,有一個新的評論,現在我只有代碼發佈發現新的註釋添加與jQuery/JavaScript的

$("#comment").submit(function(event) { 
    event.preventDefault(); 
    $.post("comment.php",{"comment" : $("#comment_text").val()},function() { 
     $("#comment_text").val(""); 
    }); 
}); 

我怎樣才能檢測到有新的評論?

回答

0

如果我理解正確的,你想從該網站的其他用戶新的評論。

一個簡單的可能性是來自服務器的結果返回新評論到您的文章像這樣(更新您的代碼):

$("#comment").submit(function(event) { 
    event.preventDefault(); 
    $.post("comment.php",{"comment" : $("#comment_text").val()},function(responseData) { 
     $("#comment_text").val(""); 
     //now use response data with new comments 
     //the structure depends on you 
     for(var i = 0; i < responseData.length; i++){ 
      $("your_comment_target").append(responseData[i].message); 
     } 
    }); 
}); 

responseData創建(可能是從數據庫中讀取)在服務器上(PHP) 。更多關於將數據返回到這裏發表successhttps://api.jquery.com/jquery.post/

我認爲responseData處於JSON形式,很簡單的例子在這裏:https://jsfiddle.net/uk3nmdtr/1/

個人而言,我寧願單獨的「刷新」功能,將加載使用AJAX評論,是這樣的:

$.get("getnewcomments.php", {articleId: /*Id or some other data here*/}, 
    function(responseData){ 
     //use response same as above 
    }); 

先進的情況是使用WebSockets或一些圖書館獲得「實時」刷新。