微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
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---运行。以此类推。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐