How might you implement the interceptor pattern on client-side (browser) AJAX request/response pairs?
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 functio开发者_JS百科ns. 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?
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.
精彩评论