2014-11-23 63 views
0

我使用此代码知道我的会话在我的大学会过多少时间。检查一下资源是否可用谷歌浏览器

function checkRemaining() { 
    var xhReq = new XMLHttpRequest(); 
    xhReq.open("GET", "http://192.168.168.168/dynUserLogin.html?loginDone=1", false); 
    xhReq.send(); 

    var regex = /Login session time remaining: ([0-9]+) minutes/g; 
    var res = regex.exec(xhReq.responseText); 

    return res[1]; 
} 

但是,当我没有连接到我的大学的互联网时,它会产生错误。

当搜索这个错误时,大多数人都使用它,因为他们使用的是AdBlock ,但在我的情况(我猜别人也有),有时候资源可能无法使用。如果请求失败,我怎样才能触发一个函数?

chrome status failed

回答

1

XMLHttpRequets将tell you what the result was

if (xhReq.status === 200) { 
    // perfect! 
} else { 
    // there was a problem with the request, 
    // for example the response may contain a 404 (Not Found) 
    // or 500 (Internal Server Error) response code 
}