AJAX学习笔记
一.什么是AJAX?
AJAX是Asynchronous Javascript And XML的简写,即异步的javascript和xml。AJAX并不是一种技术,而是由几种技术组合而成的。
Ajax包括: javaScript:
XMLHttpRequest:浏览器内置的用以进行异步数据发送和接收的对象,是Ajax的核心对象
Css+div:
DOM模型:
Xml:XML仅是一种传输数据的格式,在ajax应用中常以xml格式在c/s间交换数据;
Html:
二.Ajax的用途
Ajax是一种不用刷新整个页面便可与服务器通讯的办法
1.举个列子:我们在百度搜索时,我们输入想要搜索的东西时,下面会自动弹出一些您可能要搜索的内容,这就是靠Ajax实现的
2.再举个例子,Ajax最经典的应用:谷歌地图
3.再举个例子:验证码,很多网站在登录的时候都会让你输入验证码,你可以点击“看不清换一张”对验证码进行刷新更换,而不会使整个页面刷新,这只是局部的刷新,如果是整个页面的全部刷新,可能你之前填过的用户名和密码又得清空了
三.Ajax思维方式
1. 传统的Web交互方式-同步,如下图
传统web页面的服务是基于http协议的,所以它永远也改变不了“请求—响应”的模式。你必须“点”一下,它才能动一下,而且每次都必须刷新整个页面,这也意味着服务器要将所有页面上的数据传送下来,即使你的点击只是需要改变页面上一行十个字的内容。
2.AJAX支持的web交互方式 – 异步
Ajax采用异步交互过程。Ajax在用户与服务器之间引入一个中间媒介Ajax Engine(Ajax引擎),从而消除了网络交互过程中的处理—等待—处理—等待缺点。
用户的浏览器在执行任务时即装载了Ajax引擎。Ajax引擎用JavaScript语言编写,通常藏在一个隐藏的框架中。它负责编译用户界面及与服务器之间的交互。
简单的说浏览器不再直接将请求交给服务器处理,而是给Ajax引擎,Ajax引擎再将请求给服务器处理,这样在交互过程中用户就无需等待,仍可继续操作
四、Ajax开发步骤
Ajax开发步骤分为以下五步:
1. 得到XMLHttpRequest对象
2. 设置回调函数(这个比较难于理解,下面我会做详细说明)
3. open
4. send
5. 在回调函数中处理数据
XMLHttpRequest对象有一个属性readyState,它代表的是XMLHttpRequest对象的状态。具体内容可以在W3C文档中搜索XMLHttpRequest找到
一个简单的ajax实现:ajax1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> //第一步,得到XMLHttpRequest对象(注意这是个js对象) var xmlhttp = null; if (window.XMLHttpRequest) { //针对现在的浏览器,包括IE7以上版本 xmlhttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { //针对IE5,IE6版本 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //第二步设置回调函数 xmlhttp.onreadystatechange=function(){ //第五步,在回调函数中处理数据 if(xmlhttp.readyState==4&&xmlhttp.status==200){ //xmlhttp.responseText拿到服务器响应的数据 alert(xmlhttp.responseText); //alert(xmlhttp.readyState); } } //第三步,open,只是用设置请求方式,以及url,它不发送请求 xmlhttp.open("GET","http://localhost:8080/AJAX/Ajax1Servlet"); /* 如果是Post请求方式,还需要设置一个http请求头, 具体设置: xmlhttp.open("POST","${pageContext.request.contextPath}/ajax1"); xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded"); */ //第四步,发送请求send(它是用来发送请求的,send(null)表示没有参数 ) xmlhttp.send(null); </script> </head> <body> This is my JSP page. <br> </body> </html>
Ajax3Servlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Ajax1Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//System.out.println("servlet已执行");
//回调函数中拿到的响应数据
response.getWriter().write("shuju");
response.getWriter().close();
}
}
Ajax案例1---对用户名的合法性的验证:
ajax1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> window.οnlοad=function(){ var txt=document.getElementById("t"); txt.οnblur=function(){ var value=txt.value; //第一步,得到XMLHttpRequest对象 var xmlhttp = null; if (window.XMLHttpRequest) { //针对现在的浏览器,包括IE7以上版本 xmlhttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { //针对IE5,IE6版本 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //第二步,设置回调函数 xmlhttp.onreadystatechange=function(){ //处理响应数据,当信息全部返回,并且是成功 if(xmlhttp.readyState==4&&xmlhttp.status==200){ //获得服务器返回的数据 var msg=xmlhttp.responseText; //alert(msg); //innerHTML 属性可设置或返回单元格的开始标签和结束标签之间的 HTML document.getElementById("s").innerHTML=msg; } }; //第三步,open //xmlhttp.open("POST","${pageContext.request.contextPath}/Ajax2Servlet"); //xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded"); //post请求方式,参数设置 xmlhttp.open("POST", "http://localhost:8080/AJAX/Ajax2Servlet"); xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded"); //xmlhttp.send("username="+value); //第四步,send xmlhttp.send("username="+value); } } </script> </head> <body> 用户名:<input type="text" name="username" id="t"><span id="s"></span><br /> 密码:<input type="text"> </body> </html>
Ajax1Servlet.java
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Ajax2Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
List<String> names=new ArrayList<String>();
names.add("tom");
names.add("fox");
names.add("james");
names.add("周杰伦");
PrintWriter out=response.getWriter();
String username=request.getParameter("username");
if(names.contains(username)){
out.print("<font color='red'>用户名不可用</font>");
}else{
out.print("<font color='green'>用户名可用</font>");
}
out.flush();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
效果图:
Ajax案例2--显示商品信息:ps:记得多用几个浏览器测试几次,我开始用的FireFox和360,老是测试不成功,一直找不到问题在哪,然后就换了IE浏览器测试,一下就成功了,然后又用回fireFox也能成功了,不知道是什么原因
ajax3.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> window.οnlοad=function(){ //得到id=p的文本框 var p=document.getElementById("p"); //给文本框注册一个失去焦点事件 p.οnclick=function(){ //第一步,得到XMLHttpRequest对象 var xmlhttp = null; if (window.XMLHttpRequest) { //针对现在的浏览器,包括IE7以上版本 xmlhttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { //针对IE5,IE6版本 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //第二步,设置回调函数 xmlhttp.onreadystatechange=function(){ //处理响应数据,当信息全部返回,并且是成功 if(xmlhttp.readyState==4&&xmlhttp.status==200){ //获得服务器返回的数据 var msg=xmlhttp.responseText; //alert("msgeee"); //innerHTML 属性可设置或返回单元格的开始标签和结束标签之间的 HTML document.getElementById("d").innerHTML=msg; } }; //第三步,open //xmlhttp.open("POST","${pageContext.request.contextPath}/Ajax2Servlet"); //xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded"); //post请求方式,参数设置 xmlhttp.open("GET", "http://localhost:8080/AJAX/Ajax3Servlet"); //xmlhttp.send("username="+value); //第四步,send xmlhttp.send(null); }; }; </script> </head> <body> <a href="javascript:void(0)" id="p">显示商品信息</a> <div id="d">ddd</div> </body> </html>
Ajax3Servlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Ajax3Servlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("get开始执行了");
response.setContentType("text/html;charset=utf-8");
List<Product> ps = new ArrayList<Product>();
ps.add(new Product(1,"洗衣机",1800));
ps.add(new Product(2,"电视机",3789));
ps.add(new Product(3,"冰箱",3333));
ps.add(new Product(4,"手机",33344));
PrintWriter out=response.getWriter();
StringBuilder builder = new StringBuilder();
builder.append("<table border='1'><tr><td>商品编号</td><td>商品名称</td><td>商品价格</td></tr>");
for(Product p:ps){
builder.append("<tr><td>"+p.getId()+"</td><td>"+p.getName()
+"</td><td>"+p.getPrice()+"</td></tr>");
}
builder.append("</table>");
out.print(builder.toString());
out.flush();
out.close();
System.out.println("get执行完了");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Product.java
public class Product {
private int id;
private String name;
private double price;
public Product() {
super();
}
public Product(int id, String name, double price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
ps:早就写好的东西,一直感觉内容不够丰富,不够详细,就一直没弄到博客上来,最近又一直忙着学Android,也来不及写这个了,算了先贴上来再说,本来写在Word上面的结果复制粘贴结果多出一堆的标签,然后又一段一段的粘贴到sublime上,然后再弄到博客上才没有出现那么多乱七八糟的标签