AJAX:Asynchronous JavaScript And XML(异步JavaScript和XML)
AJAX是一种用于创建快速动态网页的技术。可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容。AJAX不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。
创建XMLHttpRequest对象
var xmlHttp; if(window.XMLHttpRequest){ //针对ie7+ 及其他版本浏览器 xmlHttp=new XMLHttpRequest(); }else{ //针对ie5 ie6浏览器 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
向服务器发送请求
open(method,url,async);规定请求的类型,URL以及是否异步处理请求
- method:请求的类型;get或post
- url:文件在服务器上的位置
- async:true(异步)或false(同步)
send() 将请求发送到服务器
xmlHttp.open("get","/hello",true);
xmlHttp.send();
服务器响应
responseText:获得字符串形式的响应数据
responseXML:获得XML形式的响应数据
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
onreadystatechange事件
每当readyState改变时,就会触发onreadystatechange事件,而readyState属性存有XMLHttpRequest的状态信息
onreadystatechange:存储函数,每当readystate属性改变时,就会调用该函数。
readyState:存有XMLHttpRequest的状态,从0到4发生变化。
- 0:请求未初始化
- 1:服务器连接已建立
- 2:请求已接收
- 3:请求处理中
- 4:请求已完成,且响应已就绪
status: 200:"ok";404:"未找到页面"。
xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ document.getElementById("myDiv").innerHTML=xmlHttp.responseText; } }
完整的AJAX实例
function sendAjax(){ var xmlHttp; if(window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest(); }else{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ document.getElementById("myDiv").innerHTML=xmlHttp.responseText; } } xmlHttp.open("get","/hello",true); xmlHttp.send(); }
posted on
浙公网安备 33010602011771号