weixin_33676492 2017-07-13 07:23 采纳率: 0%
浏览 11

Ajax通话同步与异步?

I had an issue which I, after several hours of searching, solved when I stumbled upon the fact that one can set the async-option for an ajax-call to false. My code now works exactly as I expect to, but I wonder if my solution is good or if it can be solved in a better way. If my solution is bad, why do you think so? Async vs sync, what is best? Should one always strive to use async-calls as much as possible?

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!");
    }
});

In the success I call the following function:

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++;
      }
}

Without the "async: false" the data is displayed in a random order for every refresh. With the "async: false" the data displays in the correct order, every time.

Edit:

I used the following solution to avoid using async: false.

My DisplayData-function now looks like this:

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++;
     }
}
  • 写回答

2条回答 默认 最新

  • weixin_33709609 2017-07-13 07:27
    关注

    async: false is terrible practice. It is a bad solution, and there are very few cases where it would be valid. It's so bad in fact, that if you check the console you'll see a browser warning telling you not to use it.

    With regard to your issue of the order being randomised, it's because the AJAX requests in the loop all complete at different times. To solve this you should remove async: false and either:

    1. Collate the returned data together on the client and then sort() it manually before displaying.

    2. Change your server code so that you pass all data in a single AJAX call, then you can return all the required information in the correct order.

    The second option is by far the better solution as it also avoids the DDOS-ing of your server that is currently happening due to your (N blog posts + 1) requests that you're currently flooding it with.

    评论

报告相同问题?

悬赏问题

  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)/p的连乘积值
  • ¥15 VFP如何使用阿里TTS实现文字转语音?