一、什么是AJAX
AJAX(Asynchronous JavaScript and XML)异步的 JavaScript 和 XML,通过与后端接口交互,实现页面中局部刷新。
二、AJAX原理
AJAX是通过XMLHttpRequest(所有现代浏览器均支持 XMLHttpRequest 对象,IE5 和 IE6 使用 ActiveXObject)与服务器交互,获取数据后通过javascript操作DOM来显示数据。
三、XMLHttpRequest对象
1、创建XMLHttpRequest对象
functioncreateXHR(){ varxmHttp=null; if(window.XMLHttpRequest){ xmlHttp=newwindow.XMLHttpRequest(); }else{ xmlHttp=newwindow.ActiveXObject('Microsoft.XMLHTTP'); } returnxmlHttp; }
2、向服务器发送请求
向服务器发送请求,要使用XMLHttpRequest的open和send方法
open(method,url,async)
mehtod:请求的类型(POST或GET)
url:请求的URL
anync:是否是异步请求,true(异步)、false(同步),默认为异步请求
send()方法,将请求发送到服务器
send(string)
string:仅用于POST请求,发送请求所带的参数
发送GET请求
varxmlHttp=createXHR(); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ varresult=xmlHttp.responseText; //对应的处理逻辑 } } xmlHttp.open('GET','test.PHP?aa=aa&bb=bb',true); xmlHttp.send();
发送POST请求
varxmlHttp=createXHR(); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ varresult=xmlHttp.responseText; //对应的处理逻辑 } } xmlHttp.open('POST','test.PHP',true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send('aa=aa&bb=bb');
使用POST方式发送请求时,需要设置http头信息,通过send方法传递要发送的参数
当请求是异步请求时 ,需要通过onreadystatechange事件注册一些响应后的操作,如果是同步请求,只需要在send方法后直接调用xmlHttp.responseText,不需要注册onreadystatechange
onreadystatechange:每当readyState发生改变时,都会触发该事件
readyState:存储XMLHttpRequest的状态,从0到4发生变化
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
status:从服务器端返回的响应代码,比如200(就绪),404(未找到)
responseText:从服务器返回的字符串数据
responseXML:从服务器返回的XML数据,需要作为XML对象解析
四、完整实例
<?PHP $uname=$_GET('uname'); $age=$_GET('age'); $result=array( 'uname'=>$uname,'age'=>$age ); echojson_encode($result); ?>
javascript代码:
functioncreateXHR(){ varxmHttp=null; if(window.XMLHttpRequest){ xmlHttp=newwindow.XMLHttpRequest(); }else{ xmlHttp=newwindow.ActiveXObject('Microsoft.XMLHTTP'); } returnxmlHttp; } varxmlHttp=createXHR(); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ varresult=xmlHttp.responseText; alert(result); } } xmlHttp.open('GET','test.PHP?uname=kaixin&age=16',true); xmlHttp.send();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。