这是场景:

我需要通过 AJAX 从服务器(ASP.NET MVC 应用程序 + ServiceStack 服务)获取一些 JSON 数据。如果用户的 session 过期,而不是返回 JSON,我会重定向到登录页面,该页面由 jQuery 自动执行,因此 AJAX 调用的结果最终是登录表单的原始 HTML。我需要以不同的方式处理这两种情况:

  • 如果结果是 JSON 然后使用它来更新 UI 使用 .done() promise
  • 如果结果是 HTML 则弹出登录对话框。

  • 所以我必须修改传递给 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
            }
        });
    }
    

    不幸的是,无论我在 data = null 函数中执行 return null 还是 success,传递给 done() 回调的参数都包含从服务器返回的原始 data,如果 session 已过期,它可能是登录表单的 HTML。

    所以问题是,我如何告诉 jQuery 将其他内容传递给 done()

    P.S. 当然,我可以在 isLoginFormHTML() 方法中执行 updateUI 检查,但我试图避免这种情况,以便将数据检索和 UI 更新逻辑分开。

    最佳答案

    你应该使用 .then 返回一个你需要的值的 promise ,关于 promise 的一件很酷的事情就是它们链接起来。

    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
        });
    

    关于javascript - 在成功的 AJAX 调用之后修改传递给 jQuery done() 回调的参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23224330/

    10-08 22:01
    查看更多