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" οnclick="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---运行。以此类推。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值