不久前我寫了一個Ajax工具庫。這篇是對請求超時處理的補(bǔ)充。IE8/9的xmlHttPRequest對象已經(jīng)增加這方面的支持了。IE10 pre1測試也支持。如果W3C能將這兩個東東標(biāo)準(zhǔn)化多好啊,不用那么的hack方式實(shí)現(xiàn)了。
xmlhttpRequest的timeout屬性可以設(shè)置,表示在等待響應(yīng)多少毫秒之后終止。
即如果在規(guī)定的時間內(nèi)瀏覽器沒有收到響應(yīng),那么就觸發(fā)timeout事件,給xhr.ontimeout賦值為一個響應(yīng)函數(shù)后可被執(zhí)行。
主要代碼如下
01 | xhr.onreadystatechange = function (){ |
02 | if (xhr.readyState == 4){ |
03 | try { |
04 | var s = xhr.status; |
05 | if (s>= 200 && s < 300){ |
06 | //success(xhr); |
07 | } else { |
08 | //failure(xhr); |
09 | } |
10 | } catch (e){} |
11 | } else {} |
12 | }; |
13 | xhr.open(); |
14 | xhr.timeout = 1000; |
15 | xhr.ontimeout = function (){ |
16 | alert( 'request timeout' ); |
17 | } |
超時后再訪問xhr的status屬性會出異常,因此加上try catch。
新聞熱點(diǎn)
疑難解答