Ajax Redirection Handling

纵饮孤独 提交于 2020-01-03 11:14:39

问题


I bumped into a situation I've never had to address before. I have a customer who needs to make an ajax request to a URL. For internal reasons, that URL redirects to another URL whose status code needs to be accessed. Is this kind of multi-request scenario handled natively by Ajax requests?

A quick test using jQuery seems to handle the 302, do the redirection and return the content of the targeted page (I'll only need the status code in production, but the content is what "proves" the correct page is being accessed), but I can't find any indication that I can expect this to work universally. I don't know what, if any, library the client will use. Moreover, other clients are likely to use this same URL in the future and it needs to be handled the same way.

Thanks.


回答1:


You can expect this to work universally, since it's not jQuery doing the handling. This is specified behavior of the underlying XmlHtpRequest browser object that all libraries use for AJAX calls.

You can find the behavior specified here by the W3C:

If the origin of the URL conveyed by the Location header is same origin with the XMLHttpRequest origin and the redirect does not violate infinite loop precautions, transparently follow the redirect while observing the same-origin request event rules.

I've emphasized the most relevant bit here, as long as it doesn't violate same-origin policy rules (it shouldn't on your same domain), the XmlHttpRequest will get the content of final page it gets redirected to. In other words, it's the behavior you're seeing with jQuery now...it's just not jQuery doing it.




回答2:


If you look at firebug, you can actually see the redirect happening. I think you are right that you can't depend on this for every browser. But my inclination would be that most recent browsers will handle the http connection for you and do the redirect.



来源:https://stackoverflow.com/questions/4168784/ajax-redirection-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!