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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM