就像在標題中一樣,我的問題是,是否可以判斷XMLhttpRequest的打開和發送方法是否真正起作用?有沒有任何指標? 示例代碼:XMLHttpRequest打開併發送:如何判斷它是否有效
cli = new XMLHttpRequest();
cli.open('GET', 'http://example.org/products');
cli.send();
我試圖代碼故障處理這個,但我需要能夠告訴我們,如果請求失敗,這樣我就可以處理它。
就像在標題中一樣,我的問題是,是否可以判斷XMLhttpRequest的打開和發送方法是否真正起作用?有沒有任何指標? 示例代碼:XMLHttpRequest打開併發送:如何判斷它是否有效
cli = new XMLHttpRequest();
cli.open('GET', 'http://example.org/products');
cli.send();
我試圖代碼故障處理這個,但我需要能夠告訴我們,如果請求失敗,這樣我就可以處理它。
這是一個異步操作。您的腳本在發送請求時繼續執行。
您使用檢測回調狀態的變化:
var cli = new XMLHttpRequest();
cli.onreadystatechange = function() {
if (cli.readyState === 4) {
if (cli.status === 200) {
// OK
alert('response:'+cli.responseText);
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
cli.open('GET', 'http://example.org/products');
cli.send();
// note that you can't use the result just here due to the asynchronous nature of the request
適合我。謝謝。 – 2014-11-06 21:51:47
req = new XMLHttpRequest;
req.onreadystatechange = dataLoaded;
req.open("GET","newJson2.json",true);
req.send();
function dataLoaded()
{
if(this.readyState==4 && this.status==200)
{
// success
}
else
{
// io error
}
}
是。它是。 **已經諮詢瞭解釋如何使用XHR的在線資源/文檔? -1 **;閱讀一些,然後,如果還有其他不清楚的要點,請提出一個更直接的問題。 (我會推薦使用XHR包裝器,但它是一樣的想法。) – 2012-07-05 20:05:11
@pst在我看來,操作的異步性質可能合法地難以被一個新手所理解,因爲這個人可能會被阻止。這就是我回答的原因。你認爲我不應該這樣做嗎? – 2012-07-05 20:22:56
@dystroy除了這個事實,這是一個很好的例子* ..人們編寫文檔/教程是有原因的。 – 2012-07-05 20:25:56