我正在使用Asp.net MVC,我正在尝试制作帖子和评论机制,我可以发表评论和发帖,我将它们添加到不同表格中的数据库,我也可以使用Ajax从数据库到Index.cshtml页面进行评论请求通过jQuery。我已经尝试同时发布帖子和帖子的评论,我创建了 Paralel()函数,如下所示,但我不知道如何在该函数中同时发表评论和发帖。你可以帮帮我吗?感谢。
getPosts():
function getPosts() {
var toSend = new Object();
if (timestamOfLastPost == null) {
toSend.timestampFrom = 4294967295;//MAX_INT
}
else {
toSend.timestampFrom = timestamOfLastPost;
}
toSend.numberOfPosts = 2;
$.ajax({
url: '/Home/GetPosts',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(toSend),
dataType: "json",
async:true,
success:function (data) {
$.each(data.postList, function (i, post) {
postsHtml += getMessageHtml(post.title, post.message, post.ID, "", "");
});
$("#posts").html(postsHtml);
timestamOfLastPost = data.timestamp;
},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
}
getComment():
function getComment()
{
if (timestamOfLastComment == null) {
//toSend.timestampFrom = Date.now() / 1000 | 0;
toSend.timestampFrom = 4294967295;//MAX_INT
}
else {
toSend.timestampFrom = timestamOfLastPost;
}
$.ajax({
url: '/Home/getComment',
type: 'POST',
async:true,
contentType: 'application/json',
data: JSON.stringify(toSend),
dataType: "json",
success: function (data) {
$.each(data.comment, function (i) {
comment += getComment(comment.message,comment.author_Id,comment.Post_ID)
});
}
});
}
相同常
function Paralel()
{
$.when($.ajax("/Home/GetPosts"), $.ajax("/Home/Comment")).done(function(a1, a2)
{
///To take post and comment
});
}
getCommentHtml():
function getCommentHtml(message, author_Id, Post_ID)
{
var result = '';
result += "<label>";
result += message;
result += "</label>";
}
getMessageHtml():
function getMessageHtml(title, message,ID,comment_ID,comment_message) {
var result = '';
result += "<div class=\"row col-md-8\">";
result += "<div class=\"row\">";
result += "<h2>" + title + "</h2>";
result += "</div>\n";
result += "<div class=\"row\">";
result += message;
result += "</div>\n";
result += "<hr width='%100'>";
result += "<div style='margin-left:100px' class=\"row\">";
result += "<hr width='%100'>";
result += "<form action='#' method='post'>";
result += "\n<textarea id='comment";
result += ID
result += "'></textarea>\n";
result += "\n<input type='submit' class='btn btn-default' OnClick='doComment("
result += ")' value='Comment' />";
result += "</div>\n";
return result;
}
答案 0 :(得分:0)
如果您将 Paralel 功能改为此功能,则可以使用:
function Paralel() {
getPosts();
getComment()
}
您的代码在&#34; parallel&#34;中运行因为$ .ajax是异步的。
在您的示例中,您正在尝试使用promises来执行 $。当承诺(getPosts,getComment)已解决时。 $ .ajax准备承诺,但你的函数(getPosts,getComment)没有。你必须使用jQuery promises(https://learn.jquery.com/code-organization/deferreds/examples/)