Ajax定义
是一次非传统式的请求,最大的特点是浏览器不会发生跳转而访问了服务器,偷偷的请求服务器,局部刷新。
什么时候需要使用Ajax
当本次请求需要访问 服务器,不需要发生页面跳转的时候,就需要使用ajax请求。
要点:
如何创建Ajax请求对象
var request;
if(window.XMLHttpRequest){
request=new XMLHttpRequset;
}else if(window.ActiveXObject){
request=new ActiveXObiect;
}
如何给Ajax请求绑定参数
1)get请求
request.open("get","testServlet?name=zhangsan&id=222");
2)post请求
request.post("post","testServlet?name=zhangsan&id=222");
requet.setRequestHeader("context-type","application/x-www-from-urlencoded");
request.send("name=zhangsan&age=222");
如何设置访问的地址和请求的方式
<form action="testServlet" />
如何获取Ajax请求中的参数
request.onreadystatechange=function(){
var state=request.readyState;
if(state=4){
var status=request.status;
if(status==200){
var data=request.responseText;
alert(data);
}
}
}
如何从服务器响应数据给浏览器
使用Json传参 new Gson().toJson()传参
如何在浏览器获取服务器响应给ajax的数据
eval("var result="+result);
ajax同步和异步的区别
同步
代码会一句一句往下执行,效率低
异步
代码会并行,如同多线程一样,同时执行,效率高
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ajax.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script>
function goAjax(){
//创建请求对象
//alert(window.XMLHttpRequest);//火狐全版本认识,IE高版本认识
//alert(window.ActiveXObject);//IE全本认识,火狐不认识
var request;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}else if(window.ActiveXObject){
//Msxml2.XMLHTTP IE浏览器ajax引擎的版本号
request=new ActiveXObject("Msxml2.XMLHTTP");
}
//设置请求的方式和请求的地址
//request.open(method,url,async);
//method 请求方式
//url 请求的地址
//async 设置同步和异步 本质是boolean值 true 异步 false 同步 默认是异步
request.open("get","testServlet2");
//监听服务器的响应状态
//request.onreadystatechange函数,不需要自己调用,而是ajax引擎会调用,ajax引擎会判断当前的状态,
//一旦状态发生变化,则会调用一次函数。
request.onreadystatechange=function(){
//获取响应状态
var state=request.readyState;
//数据接收完成
if(state==4){
//获取响应的状态码
var status=request.status;
if(status==200){
var data=request.responseText;
eval("var perArray="+data);
for(var i=0;i<perArray.length;i++){
alert(perArray[i].name+"----"+perArray[i].age);
}
}else if(status==404){
alert("!!!!!!!");
}else if(status==500){
alert("服务器报错!");
}
}
};
//给请求绑定参数
//语法:request.send(键=值&键=值...)
request.send(null);
}
</script>
</head>
<body>
<input type="button" value="ajax请求" onclick="goAjax()" />
</body>
</html>
jquery封装的ajax的使用
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ajaxUtil.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script src='jquery-1.11.1.js'></script>
<script>
//请求方式 type 不写默认为Get 可以用get或post
//请求地址 url
//同步异步 async
//传输的参数 data 注意格式应该为json格式
//获取服务器响应的值 success 成功之后调用的函数 是一个function,会将返回的值传入给函数的参数
$(function(){
$("#btn").click(function(){
$.ajax({
type:"get",
url:"testServlet",
data:{
name:"zhangsan",
age:29
},
success:function(result){
alert(result);
}
});
});
});
</script>
</head>
<body>
<input type="button" value="测试jquery的ajax" id="btn" />
</body>
</html>
基于jquery封装的Ajax完成的三级联动
JSP页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'three.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script src="jquery-1.11.1.js"></script>
<script>
$(function(){
$.ajax({
url:"proServlet",
success:function(result){
eval("var proArray="+result);
for(var i=0;i<proArray.length;i++){
var newOpt=$("<option></option>").html(proArray[i].provinceName).val(proArray[i].provinceId);
$("#pro").append(newOpt);
}
}
});
$("#pro").change(function(){
//清除多余的城市和区县option
$("#city option:gt(0)").remove();
$("#area option:gt(0)").remove();
//选中省份的id
var proId=$(this).val();
//如果有省份id则走ajax找城市数据
if(proId){
$.ajax({
url:"cityServlet?proId="+proId,
success:function(result){
eval("var cityArray="+result);
for(var i=0;i<cityArray.length;i++){
var newOpt=$("<option></option>").html(cityArray[i].cityName).val(cityArray[i].cityId);
$("#city").append(newOpt);
}
}
});
}
});
$("#city").change(function(){
//清除多余的区县option
$("#area option:gt(0)").remove();
//选中城市的id
var cityId=$(this).val();
//如果有城市id则走ajax找区县数据
if(cityId){
$.ajax({
url:"areaServlet?cityId="+cityId,
success:function(data){
eval("var areaArray="+data);
for(var i=0;i<areaArray.length;i++){
var newOpt=$("<option></option>").html(areaArray[i].areaName).val(areaArray[i].areaId);
$("#area").append(newOpt);
}
}
});
}
});
});
</script>
</head>
<body>
省:<select id="pro" >
<option value="">--请选择--</option>
</select>
市:<select id="city" >
<option value="">--请选择--</option>
</select>
县/区:<select id="area">
<option value="">--请选择--</option>
</select>
</body>
</html>
action(controller)层
package com.xjion.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xjion.vo.Province;
import com.google.gson.Gson;
public class ProServlet extends HttpServlet {
//用于装省份的list
private List<Province> proList;
@Override
public void init() throws ServletException {
//服务器启动时 初始化省份的信息
proList=new ArrayList<Province>();
proList.add(new Province(110000, "北京市"));
proList.add(new Province(510000,"四川省"));
System.out.println("地区信息加载完成!"+proList.size());
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("content-type", "text/html;charset=utf-8");
response.getWriter().write(new Gson().toJson(proList));
}
}
package com.xjion.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xjion.vo.City;
import com.google.gson.Gson;
public class CityServlet extends HttpServlet {
//用于装城市的list
private List<City> cityList;
@Override
public void init() throws ServletException {
//服务器启动时 初始化省份的信息
cityList=new ArrayList<City>();
cityList.add(new City(110100, "市辖区", 110000));
cityList.add(new City(110200, "县", 110000));
cityList.add(new City(510100, "成都市", 510000));
cityList.add(new City(510700, "绵阳市", 510000));
System.out.println("地区信息加载完成!"+cityList.size());
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("content-type", "text/html;charset=utf-8");
//获取省份id
int proId=Integer.parseInt(request.getParameter("proId"));
//初始化一个结果的list
List<City> resultList=new ArrayList<City>();
for(City city:cityList){
if(city.getProvinceId()==proId){
resultList.add(city);
}
}
response.getWriter().write(new Gson().toJson(resultList));
}
}
package com.xjion.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xjion.vo.Area;
import com.xjion.vo.City;
import com.google.gson.Gson;
public class AreaServlet extends HttpServlet {
//用于装地区的list
private List<Area> areaList;
@Override
public void init() throws ServletException {
//服务器启动时 初始化地区的信息
areaList=new ArrayList<Area>();
areaList.add(new Area(110101, "东城区", 110100));
areaList.add(new Area(110102, "西城区", 110100));
areaList.add(new Area(110105, "朝阳区", 110100));
areaList.add(new Area(110228, "密云县", 110200));
areaList.add(new Area(110229, "庆云县", 110200));
areaList.add(new Area(510104,"锦江区",510100));
areaList.add(new Area(510106,"金牛区",510100));
areaList.add(new Area(510105,"青羊区",510100));
areaList.add(new Area(510108,"成华区",510100));
areaList.add(new Area(510722,"三台县",510700));
areaList.add(new Area(510723,"盐亭县",510700));
areaList.add(new Area(510781,"江油市",510700));
System.out.println("地区信息加载完成!"+areaList.size());
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("content-type", "text/html;charset=utf-8");
//获取省份id
int cityId=Integer.parseInt(request.getParameter("cityId"));
//初始化一个结果的list
List<Area> resultList=new ArrayList<Area>();
for(Area area:areaList){
if(area.getCityId()==cityId){
resultList.add(area);
}
}
response.getWriter().write(new Gson().toJson(resultList));
}
}
vo(po)层
package com.xjion.vo;
public class Province {
//省份的id
private int provinceId;
//省份的名字
private String provinceName;
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public Province(int provinceId, String provinceName) {
super();
this.provinceId = provinceId;
this.provinceName = provinceName;
}
public Province() {
super();
}
}
package com.xjion.vo;
public class City {
//城市的id
private int cityId;
//城市的名字
private String cityName;
//所属省份的id
private int provinceId;
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
public City(int cityId, String cityName, int provinceId) {
super();
this.cityId = cityId;
this.cityName = cityName;
this.provinceId = provinceId;
}
public City() {
super();
}
}
package com.xjion.vo;
public class Area {
//地区id
private int areaId;
//地区名字
private String areaName;
//所属城市id
private int cityId;
public int getAreaId() {
return areaId;
}
public void setAreaId(int areaId) {
this.areaId = areaId;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public Area(int areaId, String areaName, int cityId) {
super();
this.areaId = areaId;
this.areaName = areaName;
this.cityId = cityId;
}
public Area() {
super();
}
}