我想知道使用 JavaScript 检查源服务器是否可访问并可用于处理 Ajax 请求的最简单方法是什么?为了提供更多上下文:此网站上有一些用 WordPress 构建的页面,提供可过滤的帖子列表,并且每次与过滤器的交互都会发送一个 Ajax 请求。该站点配置了边缘缓存,这样如果源出现故障,访问者仍然可以访问页面的缓存版本。但是,如果访问者在这些情况下查看缓存的页面,则过滤器将不起作用,因为对源的 Ajax 请求将失败。本质上,我想要一种方法来检测访问者实际上是否正在查看边缘缓存提供的页面的静态版本,如果是,则将一个类附加到文档的
<body>
。
我想知道是否只需创建一个
XMLHttpRequest
实例并以如下方式检查其响应就足够了,或者是否有更可靠和/或更有效的方法?
const xhr = new XMLHttpRequest();
// open request to primary site domain
xhr.open('GET', 'https://example.com');
// check for response and apply class if origin is unavailable
xhr.onload = function() {
if (xhr.status === 200) {
// can perform Ajax requests and origin is available
} else {
// cannot perform Ajax requests, thus origin must not be available
document.body.classList.add("no-origin");
}
};
这是您检查可访问性所需的全部内容...
try{
let Url = new URL('https://example.com');
// all is good so proceed processing right here
} catch(e){
// The site is not accessible, continue with plan B
}