【发布时间】: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