[英]Modifying the argument passed to jQuery done() callback following a successful AJAX call
这是场景:
我需要从服务器(ASP.NET MVC应用程序+ ServiceStack服务)通过AJAX获取一些JSON数据。 如果用户的会话到期,那么我得到一个重定向到登录页面而不是返回JSON,而是由jQuery自动执行,因此AJAX调用的结果最终成为登录表单的原始HTML。 我需要以不同方式处理这两种情况:
.done()
promise更新UI 所以我必须修改传递给done()
回调的参数。 这是我到目前为止所尝试的:
function getSomeData()
{
return $.ajax(
{
/*
...set my AJAX config options...
*/,
error: function(xhr, status, errorText)
{
// handle the error
},
success: function(data)
{
// if the AJAX call returned a login form instead of expected JSON
// result (because the user's session has expired) then show a
// login dialog and resolve the jQuery promise with 'null' instead
// of original 'data'
if (isLoginFormHTML(data))
{
showModalLoginDialog(data);
data = null; // neither this...
return null; // ... nor this seem to work!
}
}
});
}
function updateUI()
{
getSomeData().done(function(jsonData)
{
if (jsonData)
{
// do something
}
});
}
不幸的是,无论我在success
函数中执行data = null
还是return null
,传递给done()
回调的参数都包含从服务器返回的原始data
,如果会话已过期,则可能是登录表单的HTML 。
所以问题是,如何告诉jQuery传递其他东西done()
?
PS当然,我可以在updateUI
方法中执行isLoginFormHTML()
检查,但我试图避免这种情况,以保持数据检索和UI更新逻辑分离。
您应该使用.then
返回对所需值的承诺。然后,承诺的一个很酷的事情是它们链接。
function getSomeData()
{
return $.ajax({
/*
...set my AJAX config options...
*/,
error: function(xhr, status, errorText)
{
// handle the error
}).then(function(data){
if (isLoginFormHTML(data)) {
showModalLoginDialog(data);
throw new Error("Unauthorized");..
}
return data;
}
});
}
这将允许你做:
getSomeData().done(function(jsonData){
//yay data
}).fail(function(){
//no data
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.