2010年1月21日 星期四

setTimeout and XMLHttpRequest not work in IE

在利用javascript製作互動式網頁時,常會利用XMLHttoRequest去詢問伺服器,並且使用SetTimeout去重複詢問。Pattern應該會長得像下面這樣。其中xmlHttp是XMLHttoRequest物件。

function startValidate() {
   xmlHttp.open("GET", url, true);
   xmlHttp.onreadystatechange = handleStateChange;
   xmlHttp.send(null);
}

function handleStateChange() {
   …
   setTimeout('startValidate()', 2000);
   …
}

然而在IE中,這樣的程式碼卻會無法正常運作。經過trace後,發現執行完一輪後,第二輪有送出request,但是無法跳到handleStateChange。setTimeout運作是沒有問題的。這樣的寫法在Firefox和Chrome中沒有問題。

google說有好幾種方法可以解。

第一種說明因為IE認為request沒有變化,所以不進行重整,建議網址上可以加上random參數。但這種方法並沒有辦法解決。

第二種說明onreadystatechange被IE銷毀,所以沒有辦法呼叫。建議xmlHttp物件重新new一次。就像下面這樣。

function startValidate() {
   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   xmlHttp.open("GET", url, true);
   xmlHttp.onreadystatechange = handleStateChange;
   xmlHttp.send(null);
}

或者是,有個非常tricky的解法,就是onreadystatechange在send送出後再進行連結的動作,因此程式碼會長得像下面這樣。

function startValidate() {
   xmlHttp.open("GET", url, true);
   xmlHttp.send(null);
   xmlHttp.onreadystatechange = handleStateChange;
}

參考資料:
[1] 关于XMLHTTP 4.0以下版本的onreadystatechange只触发一次的问题。
[2] SetTimeout not working in IE7

沒有留言: