概述
AJAX = Asynchronous JavaScript and XML
一种日渐流行的Web编程方式,具有Better、Faster、User-Friendly的特点,不是一种新的编程语言。
传统的web交互方式是同步的
必须有页面的跳转,同一个客户端对服务器的请求必须一次请求完毕才能执行下一次请求
AJAX支持web交互方式是异步的
页面无刷新的请求,ajax默认是异步的,速度快,用户体验比较好
ajax开发步骤
- 创建XMLHttpRequest对象
- 将状态触发器绑定到一个函数
- 使用open方法建立与服务器的连接
- 向服务器端发送数据
- 在回调函数中对返回数据进行处理
创建XMLHttpRequest对象
不同浏览器提供不同的支持
IE浏览器
new ActiveXObject("Msxml2.XMLHTTP");
new ActiveXObject("Microsoft.XMLHTTP");
其它浏览器(火狐)
new XMLHttpRequest();
function ajaxFunction(){
try{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
}
对象的相关方法:
方法 | 方法描述 |
---|---|
open(method,url, asynch) | 建立对服务器的调用 |
send(content) | 向服务器发送请求 |
对象的相关属性:
属性名 | 属性描述 |
---|---|
onreadystatechange | 状态回调函数 |
responseText/responseXML | 服务器的响应字符串 |
status | 服务器返回的HTTP状态码 |
statusText | 服务器返回的HTTP状态信息 |
readyState | 对象状态:0 = 未初始化 ;1 = 正在加载;2 = 已加载 ;3 = 交互中;4 = 完成 |
将状态触发器绑定到一个函数
var xmlHttp;
createXMLHttpRequest()
…
xmlHttp.onreadystatechange = callback;
这里的callback是回调函数的方法名
function callback(){
… …
}
使用open方法建立与服务器的连接
open(method,url, asynch)
- 其中method表示HTTP调用方法,一般使用"GET","POST"
- url表示调用的服务器的地址
- asynch表示是否采用异步方式,true表示异步,一般这个参数不写
范例代码
xmlHttp.open("POST", "url");
xmlHttp.open("GET", "url?name=xxx&pwd=xxx");
var url = "/ajax_demo2/valid?username="+obj.value;
//打开连接,第一个参数是请求方式,第二个参数是请求地址,第三个参数是同步还是异步,true同步,false是异步
xmlHttp.open('get', url, false);
向服务器端发送数据
注意send必须在最后调用
GET方式提交
//发送数据,如果是get请求数据是在url上传递,不需要发送数据,send必须在最后调用。
xmlHttp.send(null);
POST方式提交
xmlHttp.setRequestHeader("CONTENT-TYPE",
"application/x-www-form-urlencoded");
xmlHttp.send("name=xxx&pwd=xxx");
在回调函数中对返回数据进行处理
//接受服务器 的响应
xmlHttp.onreadystatechange = _callback;
//发送数据,如果是get请求数据是在url上传递,不需要发送数据,send必须在最后调用。
xmlHttp.send(null);
function _callback(){
//readyState==4请求完成
if(xmlHttp.readyState == 4){
//服务器响应正确
if(xmlHttp.status == 200){
//接收服务器的响应数据
var result = xmlHttp.responseText;
alert(result);
}
}
}
常用的服务器返回数据格式
- HTML片段
- JSON格式的数据
- XML格式的数据
Ajax的post请求
Ajax返回xml文档
servlet
response.setContentType("text/xml;charset=UTF-8");
if("zhangsan".equals(username)){
response.getWriter().print("<result>error</result>");
}else{
response.getWriter().print("<result>ok</result>");
}
Ajax的回调
//readyState==4请求完成
if(xmlHttp.readyState == 4){
//服务器响应正确
if(xmlHttp.status == 200){
//接收服务器的响应数据,返回文档对象
var result = xmlHttp.responseXML;
var rs = result.getElementsByTagName('result');
alert(rs[0].innerHTML);
}
}