function loadName(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();//目前主流的浏览器高版本都内置
}else{//IE5,IE6用下面的方式
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=function(){//监听状态
if(xmlHttp.readyState==4 && xmlHttp.status==200){
document.getElementById("name").value=xmlHttp.responseText;//把返回的值赋值给DOM
}
};
xmlHttp.open("get","getAjaxName",true);//true表示异步,任务发送过去了,代码可以继续向下执行,若是同步,必须到后台把任务执行完,代码才可以继续往下执行。
xmlHttp.send();//把请求发送给后台
}
带参数与不带参数的open函数写法:(如果不带的话可以放到send 函数中)
<script type="text/javascript">
function loadName(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
xmlHttp.onreadystatechange=function(){
alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
if(xmlHttp.readyState==4 && xmlHttp.status==200){
alert(xmlHttp.responseText);
document.getElementById("name").value=xmlHttp.responseText;
}
};
// xmlHttp.open("get", "getAjaxName?name=jack&age=11", true);
// xmlHttp.open("post", "getAjaxName?name=jack&age=11", true);
// xmlHttp.send();
xmlHttp.open("post", "getAjaxName", true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("name=jack&age=11");
}
</script>
XMLHttpRequest 对象响应服务器
onreadystatechange 事件
当请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息
下面是 XMLHttpRequest 对象的三个重要的属性:
onreadystatechange存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState
存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
status
200: "OK"
404: 未找到页面
如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。
属性 描述
responseText 获得字符串形式的响应数据。
responseXML 获得 XML 形式的响应数据。