我寫了一個從桌面運行的網頁,以便從公共網站上獲取信息。我正在努力做到這一點1)如果沒有互聯網連接有警報2)如果有一個互聯網連接,但以某種方式沒有正確檢索信息,用戶會收到警報。XMLHttpRequest錯誤檢查 - 寫這個更好的方法?
如果沒有互聯網連接,try and catch可以用於測試。
我正在使用xml.status代碼進行第二次測試......如果網站處於活動狀態,但所拉動的信息已被搞亂......測試條件無法按照我所需的方式工作。我試圖給xml.open一個假網站,並期待一個非200-300狀態代碼。但它不起作用,而是catch語句被激活。爲什麼是這樣?有沒有更好的方式來寫這個?
另外,在旁註中我已經返回「」;因爲使用它的調用變量不能有null或undefined:variable = getInfo(); n.setAttribute(「placeholder」,變量);
function getInfo() {
var xml = null;
xml = new XMLHttpRequest();
try {
xml.open("get", "http://example.asp", false);
xml.send(null);
if ((xml.status >= 200 && xml.status <= 300) || xml.status == 304) {
var hi = xml.responseText;
hi = hi.replace(/(\r\n|\n|\r)/gm, "");
var what1 = /winning_number_sm.*?ul/
var what2 = /\d+/g
hi = what1.exec(hi);
var temp;
for (i = 0; i < 6; i++) {
if (null !== (temp = what2.exec(hi))) {
numbers[i] = temp;
}
}
return numbers;
} else {
alert("Error Connecting to Website! You will have to eneter informatin by hand");
return "";
}
} catch (e) {
alert("No Internet Connection! You will have to enter information by hand");
return "";
}
}
不,這是嚴格的JavaScript和沒有jQuery。謝謝。 – dman