【发布时间】:2017-07-13 21:50:39
【问题描述】:
我遇到了一个问题,经过几个小时的搜索,当我偶然发现可以将 ajax 调用的异步选项设置为 false 时,我解决了这个问题。我的代码现在完全按照我的预期工作,但我想知道我的解决方案是否很好,或者是否可以以更好的方式解决。如果我的解决方案不好,你为什么这么认为?异步与同步,什么是最好的?是否应该始终尽可能多地使用异步调用?
var pageIndex = 0;
(function () {
GetData();
$(window).scroll(function () {
if ($(window).scrollTop() ==
$(document).height() - $(window).height()) {
GetData();
}
});
})();
$.ajax({
type: 'GET',
url: '/Blog/GetPostsByBlogId',
data: { "id": @Model.First().ReqBlog.Id, "pageindex": pageIndex },
dataType: 'json',
success: function (response) {
DisplayData(response);
},
beforeSend: function () {
$("#progress").show();
},
complete: function () {
$("#progress").hide();
},
error: function (response) {
alert("Error while retrieving data!");
}
});
在成功的情况下我调用了以下函数:
function DisplayData(response)
{
if (response != null) {
$.each(response, function (i, post) {
$.ajax({
async: false,
url: "/Blog/GetPostPartialView",
data: post,
type: "POST",
success: function (response) {
$("#posts-container").append(response);
}
});
});
pageIndex++;
}
}
如果没有“async: false”,则每次刷新时数据都会以随机顺序显示。使用“async: false”,数据每次都以正确的顺序显示。
编辑:
我使用以下解决方案来避免使用 async: false。
我的 DisplayData 函数现在看起来像这样:
function DisplayData(response)
{
if (response != null) {
$.each(response, function (i, post) {
$('#posts-container').append($('<div>').load("/Blog/GetPostPartialView", { Id: post.Id, Title: post.Title, Body: post.Body, Created: post.Created, Updated: post.Updated, Views: post.Views, Blog: post.Blog, Tags: post.Tags, Comments: post.Comments, Author: post.Author }));
});
pageIndex++;
}
}
【问题讨论】:
标签: jquery ajax asynchronous