我的 asp.net MVC View 中有以下代码:-
$('body').on("click", "#transferserver,#transfersd,#transferfirewall,#transferrouter,#transferswitch", function () {
$("#showoptions").dialog({
title: "Assign Selected Records To New Rack",
width: 'auto', // overcomes width:'auto' and maxWidth bug
maxWidth: 600,
height: 'auto',
modal: true,
fluid: true, //new option
resizable: false
});
var ajaxCall = $.ajax({
url: '@Url.Content("~/Rack/ShowTransferSelectedDialog")',
data: {
rackfrom: "@Model.Rack.ITsysRackID",
assettype: $(this).attr('id')//get the id for the clciked link, so that the submit button will call the associted action method.
},
type: 'get',
success: function (html) {
$('#showoptions').html(html);
$("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
}
});
$.when(ajaxCall)
.then(function (data) { showDialog(data); });
});
我有以下问题:
$when(ajaxcall)
和 on success 之间有什么区别?在上面的代码中,如果删除
$.when(ajaxCall)
对话框仍会显示。那么还有必要拥有吗?
谢谢
编辑
但我发现使用 $.when(ajaxCall)
的一个好处是我定义了一个自定义授权属性,如下所示:-
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CheckUserPermissionsAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var viewResult = new JsonResult();
viewResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
viewResult.Data = (new { IsSuccess = "Unauthorized", description = "Sorry, you do not have the required permission to perform this action." });
filterContext.Result = viewResult;
}
}
}
目前,如果用户单击链接显示对话框而他没有获得授权,他将收到包含未经授权消息的 jAlert,如下所示:- ![在此处输入图像描述][1]
但是如果我删除 $.when(ajaxCall),
那么用户将不会收到未授权消息,并且对话框将是空白的..所以有人可以提供建议吗?
最佳答案
1) 这是 jQuery 的定义 when
Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
将它用于单个 ajax 调用是没有意义的,您想将它用于 2 个或更多,因此您需要等待它们完成后再执行某些代码。
2) 我不知道 showDialog
的作用,但您的对话框已经显示,因为在您的 success
处理程序中您有 $("#showoptions")。对话框(“显示”);
。再说一遍,根本不需要在此处使用 when
关于javascript - $.when(ajaxCall) 与成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25161023/