Ajax
1同步和异步
同步现象:客户端发送请求到服务器端,当服务器返回响应之前,客户端都处于等待卡死状态
异步现象:客户端发送请求到服务器端,无论服务器是否返回响应,客户端都可以随意做其他事情,不会被卡死(也称局部刷新)
2 Ajax运行原理
页面发起请求,会将请求发送给浏览器内核中的Ajax引擎,Ajax引擎会提交请求到服务器端,
在这段时间里,客户端可以进行任意操作,
直到服务器端将数据返回给Ajax引擎后,会触发设置的事件,从而执行自定义的js逻辑代码完成某种页面功能。
所用异步访问都是ajax引擎。
3 js原生的Ajax技术(了解)
3.1步骤
1)创建Ajax引擎对象
variable=new XMLHttpRequest();
2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;(响应)
}
}
3)绑定提交地址
xmlhttp.open("GET","test1.txt",true);
如果是post提交,在发送请求之前设置一个头:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
4)发送请求
xmlhttp.send();
5)接受响应数据
第2步中的响应
3.2 XMLHttpRequest对象的三个重要属性
|
属性 |
描述 |
|
onreadystatechange |
存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。 |
|
readyState |
存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。 0: 请求未初始化 1: 服务器连接已建立 2: 请求已接收 3: 请求处理中 4: 请求已完成,且响应已就绪 |
|
status |
200: "OK" 404: 未找到页面 |
3.3实例
例1:get方式带参数提交,并接收响应
demo01.jsp:
<p> <button value="异步访问服务器" onclick="f1()">异步访问服务器</button> <span id="span1"></span> </p>
<script>
function f1(){
//1创建Ajax引擎对象
var xmlHttp=new XMLHttpRequest();
//2绑定监听
xmlHttp.onreadystatechange=function(){
//5接受响应数据
if(xmlHttp.readyState==4&&xmlHttp.status==200){
var res=xmlHttp.responseText;
alert(res);
}
}
//3绑定提交地址
xmlHttp.open("get","${pageContext.request.contextPath}/Servlet01?name=参数",true);
//4发送请求
xmlHttp.send();
}
</script>
Servlet01:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收参数
String name=request.getParameter("name");
//响应
response.getWriter().write(name);
}

例2:post方式带参数提交,并接收响应
demo02.jsp:
<p> <button value="异步访问服务器" onclick="f1()">异步访问服务器</button> <span id="span1"></span> </p>
<script>
function f1(){
//1创建Ajax引擎对象
var xmlHttp=new XMLHttpRequest();
//2绑定监听
xmlHttp.onreadystatechange=function(){
//5接受响应数据
if(xmlHttp.readyState==4&&xmlHttp.status==200){
var res=xmlHttp.responseText;
alert(res);
}
}
//3绑定提交地址
xmlHttp.open("post","${pageContext.request.contextPath}/Servlet01",true);
//post请求头
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//4发送请求
xmlHttp.send("name=post参数");
}
</script>

例3:同步和异步的比较
demo2.jsp:
<p> <button value="异步访问服务器" onclick="f1()">异步访问服务器</button> <span id="span1"></span> </p> <p> <button value="同步访问服务器" onclick="f2()">同步访问服务器</button> <span id="span2"></span> </p> <p> <button value="测试" onclick="alert()">测试</button> </p>
<script>
function f1(){
//1创建Ajax引擎对象
var xmlHttp=new XMLHttpRequest();
//2绑定监听
xmlHttp.onreadystatechange=function(){
//5接受响应数据
if(xmlHttp.readyState==4&&xmlHttp.status==200){
var res=xmlHttp.responseText;
alert(res);
}
}
//3绑定提交地址
xmlHttp.open("post","${pageContext.request.contextPath}/Servlet2",true);
//发送请求
xmlHttp.send();
}
function f2(){
//1创建Ajax引擎对象
var xmlHttp=new XMLHttpRequest();
//2绑定监听
xmlHttp.onreadystatechange=function(){
//5接受响应数据
if(xmlHttp.readyState==4&&xmlHttp.status==200){
var res=xmlHttp.responseText;
alert(res);
}
}
//3绑定提交地址
xmlHttp.open("post","${pageContext.request.contextPath}/Servlet2",false);
//发送请求
xmlHttp.send();
}
</script>
Servlet2:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//线程沉睡5秒
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//响应一个随机数
response.getWriter().write(Math.random()+"");
}
点击“异步”按钮,测试按钮可以点击
点击“同步”按钮,测试按钮不可以点击,直到5秒后返回响应信息,才可以点击

4 Json
json是一种与语言无关的数据交换的格式,作用:
使用ajax进行前后台数据交换
移动端与服务端的数据交换
4.1 json有两种格式
对象格式:{"key1":obj,"key2":obj,"key3":obj...} (特点:大扩号,键值对)
数组/集合格式:[obj,obj,obj...] (特点:中扩号,里面存对象)
对象格式和数组格式可以互相嵌套,
json的key是字符串,json的value是Object
4.2 json的解析
json是js的原生内容,这意味着js可以直接取出json对象中的数据
例1:解析对象格式
<script>
//定义json
var person={
"name":"张三",
"age":18
}
//取值
alert(person.name+":"+person.age);
</script>
例2:解析数组格式
<script>
//定义json
var persons=[
{
"name":"张三",
"age":18
},
{
"name":"李四",
"age":20
}
];
//取值
console.log(persons[0].name+":"+persons[0].age);
console.log(persons[1].name+":"+persons[1].age);
</script>

例3:解析嵌套格式(以后再加)
4.3Json的转换插件
json的转换插件是通过java的一些工具,直接将java对象或集合转换成json字符串。
常用的json转换工具有如下几种:
1)jsonlib
2)Gson:google
3)fastjson:阿里巴巴
其中Gson较常用

Jar包放到项目中
对象封装,再转化
5 Jquery的Ajax技术
共有三种方式,$.get,$.post,$.ajax,$.ajax方式最常用
5.1 $.get和$.post
1)格式:
$.get(url, [data], [callback], [type])
$.post(url, [data], [callback], [type])
2)参数说明:
url:代表请求的服务器端地址
data:代表请求服务器端的数据,参数(json格式)
callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)
type:表示服务器端返回的数据类型(jquery会根据指定的类型自动类型转换),
常用的返回类型:text、json、html等
5.2 $.ajax
1)格式:$.ajax( { option1:value1,option2:value2... } );
2)常用的option有:
async:是否异步,默认是true代表异步
data:发送到服务器的参数,建议使用json格式
dataType:服务器端返回的数据类型,常用text和json
success:成功响应执行的函数,对应的类型是function类型
type:请求方式,POST/GET
url:请求服务器端地址
例:
demo1.jsp:
<body>
<input type="button" value="get异步请求服务器" onclick="f1()"/><br>
<input type="button" value="post异步请求服务器" onclick="f2()"/><br>
<input type="button" value="ajax异步请求服务器" onclick="f3()"/><br>
<script src="${pageContext.request.contextPath}/jquery-1.11.3.min.js"></script>
<script>
function f1(){
$.get(
"${pageContext.request.contextPath}/Servlet02",
{"name":"张三","age":18},
function(data){
alert(data);
},
"text"
);
}
function f2(){
$.post(
"${pageContext.request.contextPath}/Servlet03",
{"name":"张三","age":18},
function(data){
alert(data.name);
alert(data.age);
},
"json"
);
}
function f3(){
$.ajax({
url:"${pageContext.request.contextPath}/Servlet04",
data:{"name":"张三","age":18},
type:"POST",
async:true,
success:function(data){
alert(data.name);
},
error:function(){
alert("请求失败");
},
dataType:"json"
});
}
</script>
</body>
Servlet02:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取参数
String name=request.getParameter("name");
//解决中文乱码
name=new String(name.getBytes("ISO8859-1"),"utf-8");
String age=request.getParameter("age");
System.out.println(name+"..."+age);
//解决中文乱码
response.setContentType("text/html;charset=utf-8");
//返回响应
response.getWriter().write(name+"..."+age);
}
Servlet03:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
String age=request.getParameter("age");
System.out.println(name+"..."+age);
//解决中文乱码
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("{\"name\":\""+name+"\",\"age\":"+age+"}");
}
Servlet04:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取参数
String name=request.getParameter("name");
String agestr=request.getParameter("age");
int age=Integer.parseInt(agestr);
//封装对象
User user=new User();
user.setName(name);
user.setAge(age);
//将对象转化为json
Gson gson=new Gson();
String json=gson.toJson(user); //Object类型就可以,所以什么都可以放
//解决中文乱码
response.setContentType("text/html;charset=utf-8");
//响应json串
response.getWriter().write(json);
}
结果:
Get:

Post:


Ajax:

Tips:
1)post方式中:request不用解决中文乱码,只解决response就可以
2)注意拼串技巧(Servlet03中)
6实例:验证用户名是否可用

1)register.jsp页面中添加文本框失去焦点事件:
<script>
$(function(){
$("#username").blur(function(){
var username=$("#username").val();
$.ajax({
url:"${pageContext.request.contextPath}/CheckUsernameServlet",
data:{"username":username},
dataType:"json",
type:"POST",
async:true,
success:function(data){
var isExist=data.isExist;
var info="";
if(isExist){
info="该用户名存在,请重新输入";
$("#userinfo").css("color","red");
}else{
info="该用户名可用";
$("#userinfo").css("color","green");
}
$("#userinfo").html(info);
}
});
});
});
</script>
2)CheckUsernameServlet:
public class CheckUsernameServlet extends HttpServlet {
private UsersService usersService=new UsersService();
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取参数
String username=request.getParameter("username");
//调用service层方法
boolean isExist=usersService.checkUsername(username);
//拼成json格式
response.getWriter().write("{\"isExist\":"+isExist+"}");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
3)UsersDao中方法:
//判断用户名是否可用
public int checkUsername(String username) throws SQLException{
String sql="SELECT COUNT(*) FROM users WHERE username=?";
Long count=qr.query(sql, new ScalarHandler<Long>(),username);
return count.intValue();
}
4)UsersService中方法:
//判断用户名是否可用
public boolean checkUsername(String username){
int count=0;
try {
count=usersDao.checkUsername(username);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count>0?true:false;
}


7重点
1)jquery的ajax
格式示例:
$.ajax({
url:"${pageContext.request.contextPath}/Servlet04",
data:{"name":"namestr","age":18},
type:"post",
async:true,
dataType:"json",
success:function(data){
console.log(data);
},
error:function(){
console.log("请求失败");
}
});
2)Json的解析和Gson转化插件用法

浙公网安备 33010602011771号