检测跨域XMLHttpRequests的服务器/网站支持? [英] Detect server/site support for cross-domain XMLHttpRequests?

查看:120
本文介绍了检测跨域XMLHttpRequests的服务器/网站支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣了解最小的跨浏览器Javascript代码(jQuery也很好)可能可用于验证我希望发送跨网域AJAX请求的网站是否支持 CORS



我知道jQuery有一个方法来检查浏览器是否支持它。但我真的很想检查远程网站是否也支持它。



我想我只是要检查一下HTTP头,但是当试图对不特别支持它的网站执行跨域请求时,XHR会抛出异常。



但是有一个方法检查 XMLHttpRequest 抛出的异常是由于站点不支持 CORS 而不是其他错误? (它不必支持XDomainRequest。)



在任何情况下,我不确定最好的最小/最快的跨浏览器方式来获取 HTTP HEAD 使用AJAX,我假设是轻量级方式而不是获取页面等。



知道浏览器和AJAX提供程序是否支持 CORS ,我可以选择是否发送更具特色的 JSON / CORS 请求或在必要时返回到 JSONP 请求。

解决方案

至于规范


如果出现网络错误:如果发生DNS错误,TLS协商
失败或其他类型的网络错误,应用网络错误
步骤。不要请求任何类型的最终用户互动...



否则:执行资源共享检查。如果它返回失败,应用网络错误步骤...


没有特殊的方法来识别CORS不是允许,因为在任何情况下都会应用网络错误步骤。 / p>

I am interested in seeing what minimal cross-browser Javascript code (jQuery is fine too) might be possible for verifying whether a site I wish to send cross-domain AJAX requests has support for CORS.

I know jQuery has a method to check whether the browser supports it. But I'd really like to be able to check if the remote site also supports it.

I thought I just had to check for a HTTP header but of course the XHR will throw an exception when trying to do a cross-domain request to a site which doesn't specifically support it.

But is there a way to check that an exception thrown by XMLHttpRequest was due to the site not supporting CORS rather than something else going wrong? (It doesn't have to support XDomainRequest.)

In any case I'm not sure the best minimal/fastest cross-browser way to to fetch an HTTP HEAD using AJAX, which I assume is the lightweight way rather than fetching a page, etc.

Use case: Once I know whether the browser and AJAX provider support CORS or not, I can choose whether to send the more featureful JSON/CORS requests or fall back to JSONP requests when necessary.

解决方案

As far as the specification, it's not possible.

If there is a network error: In case of DNS errors, TLS negotiation failure, or other type of network errors, apply the network error steps. Do not request any kind of end user interaction...

Otherwise: Perform a resource sharing check. If it returns fail, apply the network error steps...

There is no special way to identify the case in which CORS is not allowed, since the network error steps are applied in any case.

这篇关于检测跨域XMLHttpRequests的服务器/网站支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆