我正在编写一个函数,从网站/服务器获取 json 文件并将其保存在本地存储中,代码如下:
function donators() {
var jsonURL = "http://mywebsite.com/donators.json";
var xhr = new XMLHttpRequest();
xhr.open("GET", jsonURL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
localDataStore.set("fb_donators", xhr.responseText);
}
};
xhr.send();
}
当可以访问 json 文件时,上面的代码工作得很好,但是如果我的服务器出现故障并且无法访问该文件,我的脚本会在 xhr.send() 行停止并出现错误:
GET http://mywebsite.com/donators.json net::ERR_NAME_NOT_RESOLVED
有没有一种方法可以检测在发送请求之前是否可以到达 url,以停止发送请求并允许脚本的其余部分继续运行而不是在 xhr.send() 处停止?
谢谢!
最佳答案
您可以使用 try
block 来实现此目的。它仍然需要 HTTP 请求,但它会正常失败,并且您可以按照自己喜欢的方式处理错误。
function donators() {
var jsonURL = "http://mywebsite.com/donators.json";
var xhr = new XMLHttpRequest();
xhr.open("GET", jsonURL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
localDataStore.set("fb_donators", xhr.responseText);
}
};
xhr.timeout = 5000;
xhr.ontimeout = function() {
alert( 'The operation timed out.' );
}
try { xhr.send(); } catch( err ) {
alert( 'Error getting data: ' + err.message );
}
}
关于javascript - Ajax - 在发送请求之前检查 url 是否存在的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26824033/