【问题标题】:$.ajax and .each in JQuery, with MVC, isn't asynchronous使用 MVC 的 JQuery 中的 $.ajax 和 .each 不是异步的
【发布时间】:2011-07-21 14:09:11
【问题描述】:

我的 Ajax 调用在包裹在 .each 循环中时似乎不是异步的,相反,它们似乎在调用下一个循环之前等待每个循环完成 ..

MVC C#:

   [HttpPost]
    public JsonResult DoActionGetNextStep(JSONSubmission Submission)
    {
        SomeStruct body = new SomeStruct();
        DateTime start = DateTime.Now;
        try
        {
        System.Threading.Thread.Sleep(5000);
        body.html= "There, done";
        }
        catch (Exception e)
        {
        body.html= "There was an error: "+e.Message;
        }
        TimeSpan s = DateTime.Now - start;
        ast.Html = body.html+ "<p> c# took " +s.Seconds +"s</p>";
        return Json(body);
    }  

JQuery:

function DoActions(targets) {
$(targets).each(function () { DoAction($(this)); });
}

function DoAction(target) {
var parent = $(target).parents('div.actionReplaceable');
var JSONSubmission = { Data : "somedata" };
var Submission = JSON.stringify(JSONSubmission, null, 2);

$.ajax({
    type: 'POST',
    url: '/Main/DoActionGetNextStep',
    data: Submission,
    async: true,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (Result) {
        var html = Result.html;
        $(parent).html(html);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $(parent).html("JQuery Error: " + textStatus + "\n" + errorThrown);
    }
});
}

对于 5 个元素,这最终需要 25 秒,每个元素都报告他们的调用需要 5 秒。我以为 ajax 调用是异步的,所以这个操作总共需要 5 秒?服务器和浏览器都在我的本地主机上运行。谁能发现我错过了什么?

【问题讨论】:

  • 您的日志文件是否确认请求是同步的?我们需要排除服务器只是缓慢响应多个连续请求的可能性。
  • 你的服务器是多线程的吗?如果没有,它别无选择,只能按顺序处理每个请求。

标签: c# asp.net-mvc jquery


【解决方案1】:

没有并行处理 Ajax 调用的原因有两个:

  1. 大多数浏览器对此进行了限制,要么是因为它们只使用两个连接到它们联系的每个站点,要么是因为它们明确限制了并发 Ajax 调用。

  2. 如果您在 ASP.NET 应用程序(无论是否为 MVC)中访问会话状态,您也会遇到排他锁,导致并行连接等待。对于 MVC,有一个属性表明您的控制器操作只需要对会话状态的只读访问权限即可解决此问题。

【讨论】:

    【解决方案2】:

    您的请求应该是异步的。请在适当的地方与console.log 联系,以了解事情何时发生。

    $(targets).each(DoAction);
    
    function DoAction() {
      var $parent = $(this).parents('div.actionReplaceable'),
          JSONSubmission = { Data : "somedata" };
    
      console.log("sending request for " + this-id);
    
      $.ajax({
        type        : 'POST',
        url         : '/Main/DoActionGetNextStep',
        data        : JSON.stringify(JSONSubmission, null, 2),
        contentType : 'application/json; charset=utf-8',
        success     : function (Result) {
          console.log("received response for " + this-id);
          $parent.html(Result.html);
        },
        error       : function (XMLHttpRequest, textStatus, errorThrown) {
          console.log("received error for " + this-id);
          $parent.html("JQuery Error: " + textStatus + "\n" + errorThrown);
        }
      });
    }
    
    • 不需要target 参数。 jQuery 为回调函数正确设置了this
    • 删除target 参数后,只需将函数引用传递给.each()
    • 除非返回类型是JSON(这里好像是HTML),否则设置dataType: 'json'是错误的。
    • 设置async: true 是多余的,除非您将全局Ajax 选项配置为async: false。我希望你没有。

    【讨论】:

    • 我调用 ajax 方法 5 x 5 次,我的 (targets).each 方法完全没有必要。感谢您将我指向 console.log 以检查 ajax 调用,非常方便!
    猜你喜欢
    • 2010-12-15
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    相关资源
    最近更新 更多