同步现象:客户端发送请求到服务器端,当服务器返回响应之前,客户端都处于等待卡死状态。
异步现象:客户端发送请求到服务器端,无论服务器是否返回响应,客户端都可以随 意做其他事情,不会被卡死。
页面发起请求,会将请求发送给浏览器内核中的Ajax引擎,Ajax引擎会提交请求到服务器端,在这段时间里,客户端可以任意进行任意操作,直到服务器端将数据返回给Ajax引擎后,会触发你设置的事件,从而执行自定义的js逻辑代码完成某种页面1功能。
js原生的Ajax其实就是围绕浏览器内内置的Ajax引擎对象进行学习的,要使用js原 生的Ajax完成异步操作,有如下几个步骤:
(1)创建Ajax引擎对象
(2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)
(3)绑定提交地址
(4)发送请求
(5)接受响应数据
演示下同步和异步的区别:
ajax.html:
<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
<script type="text/javascript">
function fn1(){
//1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
var xmlHttp = new XMLHttpRequest();
//2、绑定监听 ---- 监听服务器是否已经返回相应数据
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
//5、接受相应数据
var res = xmlHttp.responseText;
document.getElementById("span1").innerHTML = res;
alert(res)
}
}
//3、绑定地址
//xmlHttp.open("GET","/ajaxServlet?name=lisi",true);
xmlHttp.open("GET","/ajaxServlet",true);
//4、发送请求
xmlHttp.send();
}
function fn2(){
//1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
var xmlHttp = new XMLHttpRequest();
//2、绑定监听 ---- 监听服务器是否已经返回相应数据
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
//5、接受相应数据
var res = xmlHttp.responseText;
document.getElementById("span2").innerHTML = res;
}
}
//3、绑定地址
xmlHttp.open("POST","/ajaxServlet",false);
//4、发送请求
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("name=wangwu");
}
script>
head>
<body>
<input type="button" value="异步访问服务器端" onclick="fn1()"><span id="span1">span>
<br>
<input type="button" value="同步访问服务器端" onclick="fn2()"><span id="span2">span>
<br>
<input type="button" value="测试按钮" onclick="alert()">
body>
html>
Servlet:
@WebServlet(name = "ajaxServlet",
urlPatterns = {"/ajaxServlet"})
public class ajaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
response.getWriter().write(Math.random()+"");
}
}
运行结果:
点击同步按钮了之后,就不能再点击测试按钮了,5秒之后结果出来;点击异步按钮之后,还能点击测试按钮,5秒之后结果也能出来。
总结:所用异步访问都是浏览器内置的ajax引擎。
json是一种与语言无关的数据交换的格式,作用:
(1)使用ajax进行前后台数据交换
(2)移动端与服务端的数据交换
json有两种格式:
对象格式:{“key1”:obj,”key2”:obj,”key3”:obj…}
数组/集合格式:[obj,obj,obj…]
例如:user对象 用json数据格式表示
{"username":"zhangsan","age":28,"password":"123","addr":"北京"}
List 用json数据格式表示
[{"pid":"10","pname":"小米4C"},{},{}]
var persons = [
{"firstname":"张","lastname":"三丰","age":100},
{"firstname":"李","lastname":"四","age":25}
];
//取出 firstname=李
alert(persons[1].firstname);
//取100
alert(persons[0].age);
注意:对象格式和数组格式可以互相嵌套
var json = {
"baobao":[
{"name":"小双","age":28,"addr":"扬州"},
{"name":"建宁","age":18,"addr":"紫禁城"},
{"name":"阿珂","age":10,"addr":"山西"},
]
};
//娶name = 建宁
alert(json.baobao[1].name);
//取addr 山西
alert(json.baobao[2].addr);
注意:json的key是字符串 jaon的value是Object
json的解析:
json是js的原生内容,也就意味着js可以直接取出json对象中的数据
jquery是一个优秀的js框架,自然对js原生的ajax进行了封装,封装后的ajax的操 作方法更简洁,功能更强大,与ajax操作相关的jquery方法有如下几种,但开发中 经常使用的有三种:
$.get(url, [data], [callback], [type])
$.post(url, [data], [callback], [type])
其中:
url:代表请求的服务器端地址
data:代表请求服务器端的数据(可以是key=value形式也可以是json格式)
callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)
type:表示服务器端返回的数据类型(jquery会根据指定的类型自动类型转换)
常用的返回类型:text、json、html等
看下例子:
<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
<script type="text/javascript" src="/js/jquery-1.11.3.min.js">script>
<script type="text/javascript">
function fn1(){
//get异步访问
$.get(
"/ajaxServlet2", //url地址
{"name":"张三","age":25}, //请求参数
function(data){ //执行成功后的回调函数
alert(data.name);
//alert(data);
},
"json"
);
}
function fn2(){
//post异步访问
$.post(
"/ajaxServlet2", //url地址
{"name":"李四","age":25}, //请求参数
function(data){ //执行成功后的回调函数
alert(data.name);
},
"json"
);
}
script>
head>
<body>
<input type="button" value="get访问服务器端" onclick="fn1()"><span id="span1">span>
<br>
<input type="button" value="post访问服务器端" onclick="fn2()"><span id="span2">span>
<br>
body>
html>
Servlet:
@WebServlet(name = "ajaxServlet2",
urlPatterns = {"/ajaxServlet2"})
public class ajaxServlet2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println(name+" "+age);
//java代码只能返回一个json格式的字符串
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("{\"name\":\"汤姆\",\"age\":21}");
}
}
Jsp关键部分:
<script type="text/javascript">
$(function(){
//为输入框绑定事件
$("#username").blur(function(){
//1、失去焦点获得输入框的内容
var usernameInput = $(this).val();
//2、去服务端校验该用户名是否存在---ajax
$.post(
"${pageContext.request.contextPath}/checkUsername",
{"username":usernameInput},
function(data){
var isExist = data.isExist;
//3、根据返回的isExist动态的显示信息
var usernameInfo = "";
if(isExist){
//该用户存在
usernameInfo = "该用户名已经存在";
$("#usernameInfo").css("color","red");
}else{
usernameInfo = "该用户可以使用"
$("#usernameInfo").css("color","green");
}
$("#usernameInfo").html(usernameInfo);
},
"json"
);
});
});
script>
Web层:
@WebServlet(name = "checkUsername",
urlPatterns = {"/checkUsername"})
public class checkUsername extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得要校验的用户名
String username = request.getParameter("username");
//传递username到service
UserService service = new UserService();
boolean isExist = false;
try {
isExist = service.checkUsername(username);
} catch (SQLException e) {
e.printStackTrace();
}
response.getWriter().write("{\"isExist\":"+isExist+"}");
}
}
Service层:
public class UserService {
public boolean checkUsername(String username) throws SQLException {
UserDao dao = new UserDao();
Long isExist = dao.checkUsername(username);
return isExist>0?true:false;
}
}
Dao层:
public class UserDao {
public Long checkUsername(String username) throws SQLException {
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select count(*) from user where username=?";
Long query = (Long) runner.query(sql, new ScalarHandler(), username);
return query;
}
}
前端关键代码:
<form class="navbar-form navbar-right" role="search">
<div class="form-group" style="position:relative">
<input id="search" type="text" class="form-control" placeholder="Search" onkeyup="searchWord(this)">
<div id="showDiv" style="display:none; position:absolute;z-index:1000;background:#fff; width:179px;border:1px solid #ccc;">
div>
div>
<button type="submit" class="btn btn-default">Submitbutton>
form>
<script type="text/javascript">
function overFn(obj){
$(obj).css("background","#DBEAF9");
}
function outFn(obj){
$(obj).css("background","#fff");
}
function clickFn(obj){
$("#search").val($(obj).html());
$("#showDiv").css("display","none");
}
function searchWord(obj){
//1、获得输入框的输入的内容
var word = $(obj).val();
//2、根据输入框的内容去数据库中模糊查询---List
var content = "";
$.post(
"${pageContext.request.contextPath}/searchWord",
{"word":word},
function(data){
//3、将返回的商品的名称 现在showDiv中
//[{"pid":"1","pname":"小米 4c 官方版","market_price":8999.0,"shop_price":8999.0,"pimage":"products/1/c_0033.jpg","pdate":"2016-08-14","is_hot":1,"pdesc":"小米 4c 标准版 全网通 白色 移动联通电信4G手机 双卡双待 官方好好","pflag":0,"cid":"1"}]
if(data.length>0){
for(var i=0;i""+data[i]+"" ;
}
$("#showDiv").html(content);
$("#showDiv").css("display","block");
}
},
"json"
);
}
script>
Web层:
@WebServlet(name = "searchWord",
urlPatterns = {"/searchWord"})
public class searchWord extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得关键字
String word = request.getParameter("word");
//查询该关键字的所有商品
ProductService service = new ProductService();
List
Service层:
public class ProductService {
//根据关键字查询商品
public List
Dao层:
public class ProductDao {
public List
转载请标明出处,原文地址:https://blog.csdn.net/weixin_41835916
如果觉得本文对您有帮助,请点击顶支持一下,您的支持是我写作最大的动力,谢谢。