AJAX即“Asynchronous JavaScript and XML”(异步的JavaScript与XML技术),指的是一套综合了多项技术的浏览器端网页开发技术。Ajax的概念由杰西·詹姆士·贾瑞特所提出[1]。
传统的Web应用允许用户端填写表单(form),当提交表单时就向网页服务器发送一个请求。服务器接收并处理传来的表单,然后送回一个新的网页,但这个做法浪费了许多带宽,因为在前后两个页面中的大部分HTML码往往是相同的。由于每次应用的沟通都需要向服务器发送请求,应用的回应时间依赖于服务器的回应时间。这导致了用户界面的回应比本机应用慢得多。
与此不同,AJAX应用可以仅向服务器发送并取回必须的数据,并在客户端采用JavaScript处理来自服务器的回应。因为在服务器和浏览器之间交换的数据大量减少,服务器回应更快了。同时,很多的处理工作可以在发出请求的客户端机器上完成,因此Web服务器的负荷也减少了。
异步刷新:即如果网页中某一个地方需要修改,异步刷新可以 只刷新需要修改的地方,而页面中其他地方保持不变
js实现:
XMLHttpRequest对象的方法:
open(方法名(提交方式get|post),服务器地址,true(是否异步)):与服务器建立连接
send:
get:send(null)(参数写在open方法中的服务器地址中(index?mobile=sdf)
post:send(参数值)
setRequestHeader(header,value)
get:不需要设置此方法
post:需要设置:
a-如果请求元素中包含了 文件上传
setRequestHeader(“Context-Type”,“multipart/form-data”)
b-不包含 文件上传
setRequestHeader(“Context-Type”,“application/x-www-form-urlencoded”)
XMLHttpRequest对象的属性
readState:请求对象(每个状态都会调用一次回调函数)
state:响应状态
只有ready’state==4 并且 status == 200 为正常
onreadystatechange:回调函数(接收服务端的返回值)(若a是b的回调函数:则当b函数执行完后会调用a函数)
responseText:响应格式为String
responseXML:响应格式为XML
示例:
<script type="text/javascript">
function register(){
var mobile = document.getElementById("mobile").value;
//通过ajax异步方式请求服务端(form-action会全局刷新)
//不加var变量 则该变量是全局变量
xmlHttpRequest = new XMLHttpRequest();
//设置xmlHttpRequest对象的回调函数
xmlHttpRequest.onreadystatechange = callBack;
xmlHttpRequest.open("post","mobileServlet",true);
//设置post方式的头信息
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//参数为键值对的形式
xmlHttpRequest.send("mobile="+mobile);
}
//定义回调函数(接收服务端的返回值)
function callBack(){
if(xmlHttpRequest.readyState == 4&& xmlHttpRequest.status == 200){
//接收服务端返回的数据
var data = xmlHttpRequest.responseText;//服务端返回值为String格式
if(data == "true"){
alert("此号码已存在!");
}else{
alert("注册成功!");
}
}
}
function registerGet(){
var mobile = document.getElementById("mobile").value;
//通过ajax异步方式请求服务端(form-action会全局刷新)
//不加var变量 则该变量是全局变量
xmlHttpRequest = new XMLHttpRequest();
//设置xmlHttpRequest对象的回调函数
xmlHttpRequest.onreadystatechange = callBack;
xmlHttpRequest.open("post","mobileServlet?mobile="+mobile,true);
//设置post方式的头信息
//xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//参数为键值对的形式(get方式中为null)
xmlHttpRequest.send(null);
}
</script>
<title>Insert title here</title>
</head>
<body>
号码:<input type = "text" id = "mobile">
<input type="button" value="注册" onclick="registerGet()">
</body>
</html>
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
String mobile = request.getParameter("mobile");
PrintWriter out = response.getWriter();
if("123456".equals(mobile)){
out.write("true");//servlet以输出流的方式 将信息返回给客户端
}else{
out.write("false");
}
out.close();
}