当包装在.each循环中时,我的Ajax调用似乎不是异步的,而是在调用下一个..时似乎等待每个完成。
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秒钟?服务器和浏览器都在我的本地主机上运行。谁能发现我所缺少的东西?
最佳答案
您的请求应该是异步的。在适当的地方检查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'
是错误的。除非将全局Ajax选项配置为
async: true
,否则设置async: false
是多余的。我希望你没有。关于c# - 使用MVC的JQuery中的$ .ajax和.each不是异步的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6777397/