我使用 jQuery
来设置一系列函数调用,其中两个是对 ASP.NET MVC
操作(在同一 Controller 中)的 ajax 调用。通常,在第一次尝试时,第一个 AJAX 调用永远不会运行,并且进程会挂起。 Action
中的断点永远不会被击中,并且加载对话框永远显示它的漂亮外观。
不具有相同功能的不同代码路径 (thisActionCanHangAjax
) 似乎没有问题,但我并不是 100% 相信这一点。
我可以取消该过程(刷新页面、超时、关闭对话框)。我第二次单击该按钮时,它将毫无问题地完成,并且如预期的那样又好又快。
我对使用延迟/ promise 的 jQuery 很陌生,所以我希望我在这里(或在 Controller 中,但这似乎不太可能)做错了一些愚蠢的事情。
jQuery 链和 javascript 如下所示:
// <input type="button" onclick="fancySubmit()">Go Speed Racer Go</input>
function fancySubmit() {
jQuery.when()
.then(openLoadingBox)
.then(thisActionCanHangAjax) // this one sometimes hangs/etc. call doesn't reach MVC
.then(getAdditionalDataAjax)
.then(submitSimpleForm)
.done(closeLoading) // modal('hide')
.fail(showLoadingError);
}
function thisActionCanHangAjax() {
// POSSIBLE ISSUES HERE? this action returns JSON on success, but we don't care.
// any errors raise a 500 with custom message
return $.post('@Url.Action("ThisActionCanHangAjax")', $("#basicForm").serialize());
}
function getAdditionalDataAjax() {
return $.getJSON('@Url.Action("GetAdditionalDataAjax")');
}
function submitSimpleForm(jsonDataFrom_getAdditionalDataAjax) {
// create form and append to body, post form, delete <form> element
return true;
}
function openLoadingBox() {
// MAYBE THE ISSUE IS HOW I AM DOING THIS ?
var dfd = new jQuery.Deferred(function () { $("#loading-dialog").modal('show'); });
$("#loading-dialog").on('shown', function () { dfd.resolve(); });
return dfd.promise();
}
ASP.NET MVC 片段非常简单,经过测试的代码。签名如下所示:
[HttpPost] public ActionResult ThisActionCanHangAjax(TheModel model)
{
try { return new JsonNetResult(new { ok = true }); }
catch (Exception e) { return new HttpStatusCodeResult(500, e.Message); }
}
[HttpGet] public ActionResult GetAdditionalDataAjax() {
// just reads a bunch of basically static stuff, and returns it.
return new JsonNetResult(new {name="Paula", level="Brillant" });
}
就其值(value)而言,我们无法在生产中调试服务器端,并且开发也不是完美的复制(例如,我们没有一个巨大的 IBM 大型机支持这一点)因为事实上该操作执行良好/快速/经过充分测试,我不认为这是一个问题。我们只是像往常一样使用相同的函数,但是来自 AJAX,而不是作为另一个操作的一部分。
最佳答案
我想你想要:
jQuery.when(openLoadingBox)
.then(thisActionCanHangAjax) // this one sometimes hangs/etc. call doesn't reach MVC
.then(getAdditionalDataAjax)
.then(submitSimpleForm)
.done(closeLoading) // modal('hide')
.fail(showLoadingError);
你不能像这样将 .when()
留空
当然,注释行永远不会发生并挂起,你说的是当什么都没有完成时,然后执行此操作......所以,它永远不会发生
关于javascript - $.deferred() 链中的第一个 ajax 调用永远不会到达那里,但第二次单击按钮可以正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27479455/