Ajax 的onreadystatechange事件注意事項.

<script type="text/javascript">   
   function createXHR() { var request = false; try { request = new XMLHttpRequest();//最重要的對象.
            } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = false; } } } if (!request) alert("Error initializing XMLHttpRequest!"); } function AjaxTest() { var xhr = createXHR(); xhr.onreadystatechange = function () { if (xhr.readystate == 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { alert(xhr.responseText); } else { alert("Request was unsuccessful:" + xhr.status); } } }; //必須在調用open()以前指定onreadystatechange事件處理程序,才能確保跨瀏覽器兼容性.
            xhr.open("get", "test.txt", true); xhr.send(null); //注意:事件處理程序中使用了xhr對象,沒有使用this對象,緣由是onreadystatechange事件處理程序的做用域問題.
            //若是使用this對象,在有的瀏覽器中會致使函數執行失敗,或者致使異常.所以使用實際的xhr對象實例變量比較靠譜.
 } </script>
相關文章
相關標籤/搜索