ajax学习
之前学习了ajax,但是对onreadystatechange不理解,今天又学习了一下 先看例子 <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> <script type="text/javascript" charset="utf-8"> function loadName() { var xmlHttp; if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } alert("readState的状态---:"+xmlHttp.readyState+";statuds的状态---:"+xmlHttp.status); xmlHttp.onreadystatechange=function(){ alert("readState的状态:"+xmlHttp.readyState+";statuds的状态:"+xmlHttp.status); if(xmlHttp.readyState==4 && xmlHttp.status){ alert(xmlHttp.responseText); } }; //-------------------------------------------------------------------- /* get方式 xmlHttp.open("get","getAjaxNameServlet?name=张三&age=33",true); xmlHttp.send(); */ //--------------------------------------------------------------------- /* post方式 */ xmlHttp.open("post","getAjaxNameServlet",true); xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send("name=jack&age=11"); } </script> </head> <body> <div style="text-align: center"> <div><input type="button" onclick="loadName()" value="ajax请求" /> <input type="text" name="name" id="name" /></div> </div> </body> </html> 这个例子分别用get,post方式请求,其中onreadystatechange存储函数(或函数名),每当readyState 属性改变时,就会调用该函数。 XMLHttpRequest 的状态。从0 到4 发生变化。
我们发现xmlHttp.onreadystatechange指向了一个函数,这个函数是在xmlHttpRequest.readyState发生改变的时候触发。现在我们点击一个button,触发了一个loadName函数。函数往下走,第一步是创建XMLHttpRequest对象,当它完毕的时候,xmlHttpRequest.readyState的值是0(alert跟踪得到的),然后打印出readyState的状态,程序继续往下走,xmlHttp.onreadystatechange=function()---,因为状态没有改变(xmlHttpRequest.readyState的值是0),所以不触发函数,紧接着是open(),这个函数发生了之后xmlHttp.readyState的值是1了,那么就会有一个断点在Open()函数处断开,紧接着又返回到xmlHttp.onreadystatechange =function---运行,然后再执行Send()函数,这个函数发生了之后xmlHttp.readyState的值是2了,接着又返回到xmlHttp.onreadystatechange = function---运行。以此类推。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |