关键步骤有:
·创建XMLHttpRequest对象
·设置回调函数
·初始化XMLHttpRequest对象
·发送请求
·处理响应
所谓的Ajax,即异步的JavaScript和XML。它是使用JavaScript通过XMLHttpRequest对象异步发送请求到服务器,并获得返回结果,再根据结果,使用JavaScript和css局部更新相应网页的任务的过程,其中XML用来封装请求和响应数据,css用来美化网页样式。
以上便是Ajax流程
Ajax的关键元素包括:JavaScript语言、DOM(文档对象模型)、CSS样式表、XMLHttpRequest对象
1、创建XMLHttpRequest对象的语法
xmlHttpRequest = new ActiveXObject(“Microsoft.XMLHTTP”);——老版本IE语法
xmlHttpRequest = new XMLHttpRequest();
2、XMLHttpRequest对象的常用方法和属性
使用Ajax发送请求及处理响应
实现Ajax的过程分为发送请求和处理响应两个步骤。发送请求可以分为两种方式:GET方式和POST方式。处理响应也分为两种方式:处理文本响应和处理XML响应。
1、发送Get请求及处理文本方式响应
关键代码:
//1、创建XMLHttpRequest对象
if(window.XMLHttpRequest){//返回值为true时,说明是新版本IE或其他浏览器
xmlHttpRequest = new XMLHttpRequest();
}else{//返回值为false,说明是老版本IE
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
//2、设置回调函数
xmlHttpRequest.onreadystatechange = callBack;
//3、初始化XMLHttpRequest组件
xmlHttpRequest.open("GET",url,true);
//4、发送请求
function callBack(){
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
var b = xmlHttpRequest.responseText;
......
}
}
2、发送POST请求及处理文本方式响应
关键代码:
//1、创建XMLHttpRequest对象
if(window.XMLHttpRequest){//返回值为true时,说明是新版本IE或其他浏览器
xmlHttpRequest = new XMLHttpRequest();
}else{//返回值为false,说明是老版本IE
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
//2、设置回调函数
xmlHttpRequest.onreadystatechange = callBack;
//3、初始化XMLHttpRequest组件
xmlHttpRequest.open("POST",url,true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4、发送请求
var userinfo = "uname=" + uname; // 需要发送的数据信息
xmlHttpRequest.send(userinfo);
3、发送GET请求及处理XML方式响应
表1-2 XmlDocument对象的常用属性
以下是回调函数处理XML响应方式
function callBack(){
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
var dom = xmlHttpRequest.responseXML;//获取服务器端返回的XML形式的文档对象
if(dom){
var userNodes = dom.getElementByTagName("username");//获取节点名为“username”的节点对象集合
if(userNodes.length>0){
var username=userNodes[0].firstChild.nodeValue;//获取该节点对象集合中的第一个子节点值
document.getElementById("username").value=username;
}
}
}
}
以后再更新实例篇哈。