今天学了ajax技术,特地在此写下来作为复习。
一、什么是ajax?
客户端(特指PC浏览器)与服务器,可以在【不必刷新整个浏览器】的情况下,与服务器进行异步通讯的技术 即,AJAX是一个【局部刷新】的【异步】通讯技术,
说白了就是局部刷新。
二、ajax的原理如下图
附上ajax与服务器之间的几种状态,但 4是所有浏览器都支持的的
三、ajax包含的技术如下图
四、ajax开发步骤
步一:创建ajax对象,例如:ajax = createAjax();
步二:开启异步对象:例如:ajax.open(method,url)
步三:如果是POST请求则要设置请求头,例如:ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");这句话的作用是转码,如果遇到中文,将会自动转成UTF-8编码;
步四:发送请求:例如:如果是GET请求,ajax.send(null),因为GET请求的数据在请求头中就已经被发送了,即地址栏后的用?username=""
如果是POST请求,content一般写成这种形式,content = "username="+username; ajax.send(content);
步五:AJAX不断的监听服务端响应的状态变化,例如:ajax.onreadystatechange,后面写一个无名处理函数
步六:在无名处理函数中,获取AJAX的数据后,按照DOM规则,用JS语言来操作Web页面
五、ajax的应用例子,以用户登录为例,
1)使用GET方式,要注意IE浏览器,使用下面这条语句,防止IE自动缓存相同内容不刷新,
var url = "${pageContext.request.contextPath}/AjaxUserServlet?username="+username+"&time="+new Date().getTime();
jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> 通过使用GET,POST方式来使用ajax验证用户名是否重复 用户名:
java后台代码:在ajax与java后台之间使用流来传递数据的
package cn.itcast.js.user;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxUserServlet extends HttpServlet { /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); byte [] buf = username.getBytes("ISO8859-1"); username = new String(buf,"UTF-8"); String tip = "可以注册"; if("杰克".equals(username)) { tip = "该用户已注册"; } System.out.println(username); response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(tip); pw.flush(); pw.close(); } }
GET实现效果:
2)、POST方式实现ajax登录验证
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> 通过使用GET,POST方式来使用ajax验证用户名是否重复 用户名:
外部js代码:
//外部js文件
function createAjax()
{
var ajax =null;
try{
ajax = new ActiveXObject("microsoft.xmlhttp");
}catch(e1)
{
try{ ajax = new XMLHttpRequest(); }catch(e2) { alert("你的浏览器不支持AJAX异步对象"); } } return ajax; }
java后台代码:
package cn.itcast.js.user;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AjaxUserServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String tip = "images/MsgSent.gif";
if("杰克".equals(username))
{
tip = "images/MsgError.gif";
}
System.out.println(username);
resp.setContentType("text/html;charset=UTF-8");
PrintWriter pw = resp.getWriter();
pw.write(tip);
pw.flush();
pw.close();
}
}
}
}
PSOT实现效果:
六、除了这种方式,当然后续还会利用xml实现验证二级下拉框联动
注意:使用xml传输数据和使用html传输数据相应的response设置也不一样,
xml:response.setContentType("text/xml;charset=UTF-8");
xml:response.setContentType("text/html;charset=UTF-8");
jsp代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> 通过使用GET,POST方式来使用ajax验证用户名是否重复 用户名:
外部js代码:
//外部js文件
function createAjax()
{
var ajax =null;
try{
ajax = new ActiveXObject("microsoft.xmlhttp");
}catch(e1)
{
try{ ajax = new XMLHttpRequest(); }catch(e2) { alert("你的浏览器不支持AJAX异步对象"); } } return ajax; }
java代码实现
package cn.itcast.js.province;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ProvinceCityServlet extends HttpServlet { /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String province = request.getParameter("province"); System.out.println(province); String city = ""; if("广东".equals(province)) { city="广州 "+"深圳 "+"惠州 "; }else if("湖北".equals(province)) { city = "武汉 "+"黄冈 "+"宜昌 "; } response.setContentType("text/xml;charset=utf-8"); PrintWriter pw = response.getWriter(); pw.write(""); pw.write(""); pw.write(city); pw.write(" "); pw.flush(); pw.close(); } //需求实现从数据库中读取数据并添加到xml文件中 }
最后实现效果:
七、最后一点根据省份从数据库中取出对应的城市数据,话不多说直接上代码
package cn.itcast.js.province; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ProvinceCityServlet extends HttpServlet { private static PreparedStatement pst = null; private static Connection con = null; private static ResultSet rs = null; String sql = ""; //首先要指定ArrayList初始化 private Listlist = new ArrayList (); /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //十分重要,清除之前存在的数据 list.clear(); String province = request.getParameter("province"); //System.out.println(province); //String city = ""; //从数据库中查询获得 try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=Employee","sa","*******"); //从两个表中去查找 sql = "select c.cName from t_city c,t_province p where p.pName =? and c.pName = p.pName"; pst = con.prepareStatement(sql); //下标从1开始,设置占位符必须在con.prepareStatement(sql);语句之后 pst.setString(1, province); rs = pst.executeQuery(); while(rs.next()) { //System.out.println(rs.getString(1)); list.add(rs.getString(1)); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(con != null) try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(pst != null) try{ pst.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(rs != null) try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /**if("广东".equals(province)) { //city="广州 "+"深圳 "+"惠州 "; }else if("湖北".equals(province)) { city = "武汉 "+"黄冈 "+"宜昌 "; }*/ response.setContentType("text/xml;charset=utf-8"); PrintWriter pw = response.getWriter(); pw.write(""); pw.write(""); for(int i=0;i "); pw.flush(); pw.close(); } //需求实现从数据库中读取数据并添加到xml文件中 }) { pw.write(" "+list.get(i)+" "); } // pw.write(city); pw.write("
jsp文件同上,这里出了两个问题,一是rs.getString("pName");会报错,原因是写错了rs.getString("cName");或者rs.getString(1);下标从一开始,第二个就是list集合元素要清空,如果不清空就会出现下面这种情况