Javascript 如何处理 XHR 错误显示消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14715866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:43:55  来源:igfitidea点击:

How to handle XHR error display messages?

javascriptjqueryxmlhttprequest

提问by Varaquilex

I'm trying to fetch some content from another source using XHR as shown below:

我正在尝试使用 XHR 从另一个来源获取一些内容,如下所示:

function fetchPage(str)
{
    if(str=="")
    {
        document.getElementById("table").innerHTML="";
        resetFilters();
        $('#progress').hide();  //fetching progress bar <div>
        return;
    }
    if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    else // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange=postCallback;
    xmlhttp.open("GET", "fetch.php?url=http://www.sis.itu.edu.tr/tr/ders_programlari/LSprogramlar/prg.php?fb="+str, true);
    xmlhttp.send();

// any stuff that goes here will happen before callback
//  (this is a good place to update a UI element showing a call is resolving.)
//  (for example a spinner or text saying "fetching")
$('#progress').show();
progressFetching();
switch(xmlhttp.readyState){ //loading bar adjustments
    case 0:
        $('.bar').css("width","0%");
        $('.bar').text("0%");
        break;
    case 1:
        $('.bar').css("width","25%");
        $('.bar').text("25%");
        break;
    case 2:
        $('.bar').css("width","50%");
        $('.bar').text("50%");
        break;
    case 3:
        $('.bar').css("width","75%");
        $('.bar').text("75%");
        break;
}
}



function postCallback()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
    progressDone();   //loading is finished
    $('#error').hide();
    document.getElementById("table").innerHTML=xmlhttp.responseText;                     

    // continue to process post callback.
    resetFilters();
}
else {
    // report error with fetch

    /*if(xmlhttp.status==404 || xmlhttp.responseText == "")
        $('#error').show();*/
    //$('#error').show();
}
}

I want my page to display error when connection timeout occurs, or when the computer doesn't have an internet connection (maybe a disconnection occurred while hanging around) or any other situation where the webpage fails to fetch the contents of the other source.

我希望我的页面在发生连接超时时显示错误,或者当计算机没有互联网连接(可能在闲逛时断开连接)或网页无法获取其他来源的内容的任何其他情况。

Using the code above, in the elseblock, if I go for if(xmlhttp.status==404 || xmlhttp.responseText == "")in the /* */comment section, I won't get an error unless its not a 404 error. If i go for //comment section, error will be displayed after the fetching process is started until it is completed, i.e. between xmlhttp.readyState = 0through xmlhttp.readyState = 4. How can I display connection error messages using these attributes or something else?

使用上面的代码,在else块中,如果我if(xmlhttp.status==404 || xmlhttp.responseText == "")/* */评论部分中查找,除非不是 404 错误,否则我不会收到错误。如果我去//评论部分,在获取过程开始后直到它完成,即在xmlhttp.readyState = 0通过之间,将显示错误xmlhttp.readyState = 4。如何使用这些属性或其他属性显示连接错误消息?

Thank your for your attention:)

感谢您的关注:)

回答by Kolby

According to this stackoverflow: XMLHttpRequest (Ajax) Error

根据这个stackoverflow:XMLHttpRequest (Ajax) 错误

 xmlhttp.onreadystatechange = function (oEvent) {
   if (xmlhttp.readyState === 4) {
     if (xmlhttp.status === 200) {
       console.log(xmlhttp.responseText)
     } else {
       console.log("Error", xmlhttp.statusText)
     }
   }
 }

回答by Hogan

The problem is my template in prior question was flawed. I believe this will work better because it creates a closure to pass the variable you need to work with.

问题是我在先前问题中的模板有缺陷。我相信这会更好,因为它创建了一个闭包来传递您需要使用的变量。

Once again, I did not test this so it might have typos and bugs -- nor did I change anything except how postCallback()is invoked and added a parameter to it.

再一次,我没有测试它,所以它可能有拼写错误和错误——我也没有改变任何东西,除了如何postCallback()调用和向它添加一个参数。

function fetchPage(str)
{
    if(str=="")
    {
        document.getElementById("table").innerHTML="";
        resetFilters();
        $('#progress').hide();  //fetching progress bar <div>
        return;
    }
    var xmlhttp;

    if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    else // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange=function () { postCallback(xmlhttp); };
    xmlhttp.open("GET", "fetch.php?url=http://www.sis.itu.edu.tr/tr/ders_programlari/LSprogramlar/prg.php?fb="+str, true);
    xmlhttp.send();

// any stuff that goes here will happen before callback
//  (this is a good place to update a UI element showing a call is resolving.)
//  (for example a spinner or text saying "fetching")
$('#progress').show();
progressFetching();
switch(xmlhttp.readyState){ //loading bar adjustments
    case 0:
        $('.bar').css("width","0%");
        $('.bar').text("0%");
        break;
    case 1:
        $('.bar').css("width","25%");
        $('.bar').text("25%");
        break;
    case 2:
        $('.bar').css("width","50%");
        $('.bar').text("50%");
        break;
    case 3:
        $('.bar').css("width","75%");
        $('.bar').text("75%");
        break;
}
}



function postCallback(xmlhttp)
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
    progressDone();   //loading is finished
    $('#error').hide();
    document.getElementById("table").innerHTML=xmlhttp.responseText;                     

    // continue to process post callback.
    resetFilters();
}
else {
    // report error with fetch

    /*if(xmlhttp.status==404 || xmlhttp.responseText == "")
        $('#error').show();*/
    //$('#error').show();
}
}