简体   繁体   English

Ajax - 在发送请求之前检查 url 是否存在的功能

[英]Ajax - Function to check if url exists before send request

I am writing a function to grab a json file from a website/server and save it in local storage with the code:我正在编写一个函数来从网站/服务器获取一个 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();
}

The above code works perfectly fine when the json file can be reached, but if my server goes down and the file cannot be reached my script halts at the line with xhr.send() with the error:当可以访问 json 文件时,上面的代码工作得很好,但是如果我的服务器出现故障并且无法访问该文件,我的脚本将在 xhr.send() 行停止并出现错误:

GET http://mywebsite.com/donators.json net::ERR_NAME_NOT_RESOLVED 

Is there a way I can detect check if url can be reached before the send request to stop the send the request and allow the rest of my script to continue to run instead of getting halted at xhr.send()?有没有一种方法可以检测在发送请求之前是否可以到达 url 以停止发送请求并允许我的脚本的其余部分继续运行而不是在 xhr.send() 处停止?

Thanks!谢谢!

You can use a try block for this.您可以为此使用try块。 It still requires the HTTP request, but it will fail gracefully and you can handle the error any way you'd like.它仍然需要 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 );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM