如何在客户端(浏览器)AJAX 请求/响应对上实现拦截器模式?
让我从一个现实生活中的用例开始:
DWR 在服务器端身份验证时变得混乱由于会话过期,过滤器尝试将 AJAX 请求重定向到登录页面。您想要添加一些过滤器,以便
- HTTP 状态代码等于 3xx 的请求执行客户端重定向,例如 window.location = ...login.html
- 请求其状态代码等于 2xx 的内容将原封不动地转发到任何已注册的处理程序,例如 DWR。
- 其他代码,例如 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
- Requests whose HTTP status code equal 3xx execute a client-side redirect, like window.location = ...login.html
- Request whose status codes equal 2xx are forwarded on - unchanged - to any registered handlers, like DWR.
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经实现了一些在 jQuery 环境中部分实现这一目标的东西。 jQuery AJAX 函数除了
error
和success
函数外,还具有complete
函数。因此,您可以执行类似的操作来根据返回的状态代码进行拦截和重定向:...等。不完全“原生”,但在 jQuery 内部相对干净。
I have implemented something which partially acheives this in a jQuery environment. A jQuery AJAX function has, as well as
error
andsuccess
functions, acomplete
function as well. So, you can do something like this to intercept and re-direct based on the returned status code:...etc. Not quite 'natively', but relatively clean from within jQuery.