AJAX是一种网页局部刷新技术。
全称:Asynchronous JavaScript and XML:异步的JavaScript和XML
AJAX的运行仅仅需要浏览器支持JavaScript运行即可
AJAX基于现有的Internet标准,联合使用:XMLHttpRequest对象(异步的与服务器交换数据)、JavaScript/DOM(信息的显示/交互)、CSS(给数据定义样式)、XML(作为转化数据的格式)来实现AJAX技术。
使用步骤:
1:创建XMLHttpRequest对象。
所有的现代化的浏览器均支持XMLHttpRequest对象。(其中IE5、6版本使用ActiveXObject对象)
XMLHttpRequest用于在后台与服务器交换数据。
var xmlhttp;
if (window.XMLHttpRequest){
//window.XMLHttpRequest用于判断浏览器是否支持XMLHttpRequest。
xmlhttp = new XMLHttpRequest();
}else{
//专门为IE5、6执行
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
以上代码在javaScript中创建了XMLHttpRequest对象--xmlhttp。
2:向服务器发送请求。
使用XMLHttpRequest对象的open()和send()方法:
open(method,url,adync):规定请求的类型、URL以及是否异步处理请求。例:xmlhttp.open("GET","ajax_info.txt",true);
method:请求的类型:GET或POST。一般情况下使用GET方法可以满足要求,使用更简单也更快。但是,在无法使用缓存文件(更新服务器上的文件或数据库)、向服务器发送大量数据以及发送包含位置字符的用户输入时,应该使用post。
url:文件在服务器上的位置
async:true(异步)或false(同步)
send(String):将请求发送到服务器。String参数仅用于为post请求添加数据。使用GET时参数为空就好。
3:服务器响应。
使用XMLHttpRequest对象的responseText或者responseXML属性来获取服务器响应。
responseText:获得字符串形式的响应数据。
例:document.getElementById("MyDiv").innerHTML = xmlhttp.responseText; //把响应写进了页面。
responseXML:获得XML形式的响应数据。
如果来自服务器的响应是XML,而且需要XML对象进行解析,那么使用此。
例:
xmlDoc = xmlhttp.responseXML;
txt=""; x=xmlDoc.getElementsByTagName("ARTIST");
for(i=0;i<x.length;i++){
txt = txt + x[i].childNodes[0].nodeValue+"<br>";
}
document.getEmlemntById("myDiv").innerHTML=txt;
服务器端程序。
以servlet为例:
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet(name="process", urlPatterns={"/process"})
public class Process extends HttpServlet{
public void service (HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
String q = request.getParameter("q");
String msg = "";
if(q.equals("employee")){
msg = "小明<br>小红<br>小花";
}else if(q.equals("position")){
msg = "经理<br>秘书<br>职员";
}else if(q.equals("part")){
msg = "整车<br>车身<br>电气";
}else{
msg = "nothing";
}
response.getWriter().write(msg);
}
}
这里,response.getWriter().write(msg )即把数据写入输出流。也就是xmlhttp.responseText中。