ajax和json
Ajax
同步和异步: a标签是同步,调用完形成新的页面,页面会刷新.原页面在a标签后面的代码将不执行处于等待状态. 而异步请求不会.异步此页面的其他代码会继续执行 应用场景: 用户名是否存在的校验,百度自动补全功能,商品查找,搜索图片 注意: ajax不能跨函数,不能跨页面
异步:强大之处服务器处理不影响浏览器的其他操作,增强用户体验度
原生ajax
入门案例: 1:创建一个核心对象(XMLHttPRequest) 该对象称之为ajax引擎 2:编写onreadystatechange事件所调用的函数 回到函数 3:确定请求方式和请求路径 4:发送请求 5:处理返回结果
原生ajax案例:
index.jsp
<%-- Created by IntelliJ IDEA. User: hp Date: 2020/5/14 Time: 13:27 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <h3>原生ajax</h3> <a href="js_01.jsp">原生ajax入门</a> </body> </html>
js_01.jsp
<%-- Created by IntelliJ IDEA. User: hp Date: 2020/5/14 Time: 13:29 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="/day07/js/jquery-3.3.1.js"></script> <script> function sendAjax() { //发送sjax请求 //1:创建ajax核心对象(xmlhttprequest)ajax引擎 var xmlhttp; if(window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); }else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //2:编写onreaystatechange事件所调用的函数 xmlhttp.onreadystatechange=function () { //1:监听ajax引擎的状态 //5:处理结果 if(xmlhttp.readyState==4 && xmlhttp.status==200){ $("#spId").html(xmlhttp.responseText); } } //3:编写ajax请求的方式和地址 xmlhttp.open("post","demo1"); //4:发送请求 xmlhttp.send(); } </script> </head> <body> <input type="button" value="发送ajax请求" onclick="sendAjax()"/><br> <span id="spId"></span> </body> </html>
Demo1Servlet.java
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "Demo1Servlet", urlPatterns = "/demo1") public class Demo1Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("demo1servlet执行了"); response.getWriter().print("hello ajax 你好"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
原生ajax的属性
onreadystatechange事件 在ajax对象状态发生改变时,就会出发该时间 对象.onreadystatechange=function(){} redaystate 存在XMLHTTPRequest的状态 0:请求未初始化(见不到的就相当于还没创建对象) 1:服务器连接已建立 2:请求已接收 3:请求处理中 4:请求已完后,且响应已就绪 status 响应状态码: if(xmlhttp.readystate==4&&xmlhttp.status==200){ //执行的代码片段 } responseText 获取服务器响应回来的文本信息
原生ajax的方法
open(method,url,[async]); 设置请求的类型,请求地址以及是否异步处理请求 method:请求的类型;get或post url:文件在服务器上的位置 async:true(异步)或false(同步) send([string]); 将请求发送到服务器 string:存放post请求携带的参数 在post请求时要设置请求参数的mime类型 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
jQuery中的Ajax
$.post(url,[params],fn,[type])
发送post请求
url:请求的路径
params:请求的参数
格式1:字符串key1=value1&key2=value2
格式2:json格式:
{“key1”:“value1”,“key2”:“value2”}
fn:回调函数
function(data){
//data:响应回来的数据(xmlHttp.responseText)
}
type:返回内容的格式 text xml json
默认返回的是text类型的数据,一般不需要自己设置,设置的话一般设置为json
ajax的post请求案例:
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <h3>原生ajax</h3> <a href="js_01.jsp">原生ajax入门</a> <h3>jQuery的ajax</h3> <a href="js_02.jsp">jQuery的ajax</a> </body> </html>
js_02.jsp
<%-- Created by IntelliJ IDEA. User: hp Date: 2020/5/14 Time: 13:29 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="js/jquery-3.3.1.js"></script> <script> function sendAjax() { var url = "demo2"; var params ={"username":"汤姆","password":"123"}; function fun(data) { alert(data); } $ .post(url, params, fun,"text"); } </script> </head> <body> <input type="button" value="发送ajax请求" onclick="sendAjax()"/><br> <span id="spId"></span> </body> </html>
Demo02Servlet.java
@WebServlet(name = "Demo3Servlet", urlPatterns = "/demo2") public class Demo3Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决乱码 response.setContentType("text/html;charset=utf-8"); response.getWriter().print(request.getParameter("username")+":"+request.getParameter("password")); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
如果换为get请求则 $.get(url,[params],fn,[type])即可
$.ajax写法想发post或者get都可以
$.ajax({url,[settings]}) url:请求路径 type:请求方式 data:请求参数 success:请求成功后的回调函数 error:请求失败后调用的函数 dateType:服务器返回的数据类型 一般不需要自己设置,要设置的话一般设置为json async:设置是否为异步提交,默认为true(异步提交) eg: $.ajax({ url:url, data:params, type:"post", success:f, error:ef, async:true })
json
概述: JavaScript对象表示法,是存储和交换文本信息的语法,类似xml, 比xml更小,更快,更衣解析. 格式: 格式1:json对象 {"key":"value","key2":"value2"}//key为String类 型,value任意类型 格式2:json数组 ["aa","bb"] 格式3:混合json [{"name":"张三","age":"11"},{"name":"张三2","age":"21"}] {"student":["张三","李四"]} 获取json对象格式的值直接:对象.key
java对象转换为json数据
常见的工具类: jsonlib fastjson(阿里巴巴的) gson(谷歌的) Jackjson(为springmvc默认的转换方式)
案例一:检测用户名是否被注册
需求分析: 再注册页面上,当用户在用户名的输入框输入完成后,也就是失去焦点事件发送ajax请求,检验用户名是否存在 该用户名已存在: 提示:"该用户名已被占用" 该用户名不存在: 提示:"√" 技术分析: blur:失去焦点事件 ajax: $.ajax({ url:"", data:"", type:"", success:f, error:f, dataType:"text", async:true }) 步骤分析: 前台: 提供注册页面,给用户名的输入框添加失去焦点事件 输入框对象.blur(function(){ //发送ajax请求 })
demo1.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="js/jquery-3.3.1.js"></script> <script> //页面加载成功事件 $(function () { //用户名输入框的失去焦点事件 $("input[name='username']").on("blur",function () { //获取用户输入的name值 var username=$(this).val(); //使用ajax异步处理 $.ajax({ url:"user", data:{"username":username}, type:"post", success:function (data) { $("#nameMsg").html(data); }, dataType:"text", async:true }) }) }) </script> </head> <body> <form action=""> <table align="center" border="1px solid red" width="300px" height="100px"> <tr> <th colspan="2" align="center"> 用户表单 </th> </tr> <tr> <td>用户名:</td> <td> <input type="text" name="username"> <span id="nameMsg"></span> </td> </tr> <tr> <td>密码:</td> <td> <input type="password" name="pwd"> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" id="subId" value="提交"/> </td> </tr> </table> <br> </form> </body> </html>
UserServlet.java
@WebServlet(name = "UserServlet", urlPatterns = "/user") public class UserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //获取前端传来的userName String username = request.getParameter("username"); //调用service查看此用户名是否存在 UserService userService = new UserService(); User exist = userService.exist(username); if (exist==null) { response.getWriter().print("√"); }else{ response.getWriter().print("用户名已存在"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
UserService.java
public class UserService { public User exist(String username){ UserDao userDao = new UserDao(); return userDao.exist(username); } }
UserDao.java
public class UserDao { public User exist(String username){ try { String sql = "select * from user where name = ? "; JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); return template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username); } catch (DataAccessException e) { return null; } } }
案例二:异步自动填充
demo2.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <style type="text/css"> .content{ width:643px; margin:200px auto; text-align: center; } input[type='text']{ width:530px; height:40px; font-size: 14px; } input[type='button']{ width:100px; height:46px; background: #38f; border: 0; color: #fff; font-size: 15px } .show{ width: 535px; border: 1px solid #999; border-top: 0; display: none; } </style> <script type="text/javascript" src="js/jquery-3.3.1.js"></script> <script type="text/javascript"> //搜索框联想词的单击事件 function fn(ele) { $("input[name='word']").val($(ele).html()); } $(function () { $("input[name='word']").on("keyup",function () { $.ajax({ url:"demo2", data:{"username":$(this).val()}, type:"post", success:function (data) { if(data!="null"&&data.length>0){ var str=""; $("div>div").empty(); $.each(data,function (index,ele) { str += "<span οnclick='fn(this)'>"+ele+"</span><br>"; }); $("div>div").html(str); $("div>div").show(); }else{ $("div>div").hide(); } }, dataType:"json", async:true }) }) }) </script> </head> <body> <div class="content"> <img alt="" src="img/logo.png"><br/><br/> <input type="text" name="word"> <input type="button" value="搜索一下"> <div class="show"></div> </div> </body> </html>
Demo2Servlet.java
@WebServlet(name = "Demo2Servlet", urlPatterns = "/demo2") public class Demo2Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); List<String> userList = new UserService().likeName(request.getParameter("username")); //将list转换为json String listJson = new ObjectMapper().writeValueAsString(userList); System.out.println("listJson======="+listJson); response.getWriter().print(listJson); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
service.java
public class UserService { public User exist(String username){ UserDao userDao = new UserDao(); return userDao.exist(username); } public List<String> likeName(String username){ UserDao userDao = new UserDao(); return userDao.likeName(username); } }
dao.java
public class UserDao { public User exist(String username){ try { String sql = "select * from user where name = ? "; JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); return template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username); } catch (DataAccessException e) { return null; } } public List<String> likeName(String username){ try { String sql = "select name from user where name like ? "; JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); return template.queryForList(sql, String.class, username+"%"); } catch (DataAccessException e) { return null; } } }