Ahm*_*mel 0 javascript asp.net-mvc jquery real-time
我有一个带评论功能的新闻项目.任何添加评论的人都可以在不重新加载页面的情况下立即查看他的评论(使用ajax).问题是当user1(例如)对post1发表评论时,只有user1可以立即看到他的评论,但所有其他用户需要重新加载页面才能看到user1的评论.我怎么解决这个问题 ?
我用来获取评论的代码:
$(function () {
$("#AddComment").click(function () {
var CommentText = document.getElementById("CommetForm").innerHTML;
var UserName = document.getElementById("UserName").innerHTML;
var PostId = document.getElementById("PostId").innerHTML;
$.ajax({
url: '/PostComment/AddComment',
type: 'POST',
dataType: 'json',
cache: false,
data: { "PostId": PostId, "CommentText": OrignalCommentText },
success: function (data)
{
if (data == "P") // Commet Stored on database successfully
{
document.getElementById("PostComments-" + PostId).innerHTML +=
"<li>" +
"<div class='media'>" +
"<div class='media-body'>" +
"<a href='' class='comment-author'>"+UserName+"</a>" +
"<span class='CommetText' id='CommentText-" + PostId + "'>" + CommentText + "</span>" +
"</div>" +
"</div>" +
"</li>";
}
else // Some Error occur during storing database
{
document.getElementById("CommentError-" + PostId).innerHTML = "\nSomething went wrog, please try agin";
}
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
这个代码用于在数据库中存储注释:
private SocialMediaDatabaseContext db = new SocialMediaDatabaseContext();
[HttpPost]
public JsonResult AddComment(string PostId, string CommentText)
{
try
{
Users CurrentUser = (Users)Session["CurrentUser"];
PostComment postcomment = new PostComment();
CommentText = System.Uri.UnescapeDataString(CommentText);
postcomment.PostId = int.Parse(PostId);
postcomment.CommentFromId = CurrentUser.UserId;
postcomment.CommentText = CommentText;
postcomment.CommentDate = DateTime.Now;
db.PostComments.Add(postcomment);
db.SaveChanges();
return Json("P");
}
catch
{
return Json("F");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
983 次 |
| 最近记录: |