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>
相关文章
相关标签/搜索