如何在客户端(浏览器)AJAX 请求/响应对上实现拦截器模式?

发布于 2024-08-23 23:27:59 字数 657 浏览 2 评论 0原文

让我从一个现实生活中的用例开始:

DWR 在服务器端身份验证时变得混乱由于会话过期,过滤器尝试将 AJAX 请求重定向到登录页面。您想要添加一些过滤器,以便

  1. HTTP 状态代码等于 3xx 的请求执行客户端重定向,例如 window.location = ...login.html
  2. 请求其状态代码等于 2xx 的内容将原封不动地转发到任何已注册的处理程序,例如 DWR。
  3. 其他代码,例如 4xx 可能会触发警报,而不是消失在深渊中。

我可能不需要解释为什么这种类型的功能会有用;大多数服务器端 Web 框架都支持拦截器模式,原因与您可能希望在客户端上使用拦截器模式的原因类似。

一种(可能是糟糕的)实现可能涉及将原始 XMLHttpRequest 对象包装在接受一些过滤器函数的代理中。由于 jQuery、Prototype、ExtJS 等都已经包装了本机浏览器 AJAX 对象,因此这可能是一个额外的步骤。

这可以本地实现吗?技术挑战是什么?以前有过类似的事情吗?

Let me start with a real-life use case:

DWR is getting confused when server-side authentication filters attempt to redirect AJAX requests to the login page due to an expired session. You'd like to add some filters so that

  1. Requests whose HTTP status code equal 3xx execute a client-side redirect, like window.location = ...login.html
  2. Request whose status codes equal 2xx are forwarded on - unchanged - to any registered handlers, like DWR.
  3. Other codes, like 4xx might trigger alerts instead of disappearing into the abyss.

I probably don't have to explain why this type of functionality would be useful; most server-side web frameworks support the interceptor pattern for similar reasons you might want it on the client.

One (probably bad) implementation could involve wrapping the raw XMLHttpRequest object in a proxy which accepts some filter functions. Since jQuery, Prototype, ExtJS, etc. all wrap the native browser AJAX objects already, this could be one additional step.

This this possible to implement natively? What are the technical challenges? Has anything like this been done before?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜雨飘雪 2024-08-30 23:27:59

我已经实现了一些在 jQuery 环境中部分实现这一目标的东西。 jQuery AJAX 函数除了 errorsuccess 函数外,还具有 complete 函数。因此,您可以执行类似的操作来根据返回的状态代码进行拦截和重定向:

complete:
    function() {
        if (data.status == 301 ||
            data.status == 302 ||
            // etc.
        ) {  
            location.replace('error.html')
        } 

...等。不完全“原生”,但在 jQuery 内部相对干净。

I have implemented something which partially acheives this in a jQuery environment. A jQuery AJAX function has, as well as error and success functions, a complete function as well. So, you can do something like this to intercept and re-direct based on the returned status code:

complete:
    function() {
        if (data.status == 301 ||
            data.status == 302 ||
            // etc.
        ) {  
            location.replace('error.html')
        } 

...etc. Not quite 'natively', but relatively clean from within jQuery.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文