jQuery 第六章 jQuery在Ajax应用
1.本章目标
ajax
2.ajax
异步刷新技术,我们的网页不需要全部刷新,按需实现局部刷新,上线后台的交互
用户体验好
地图,前台验证,表单提交,修改,查询等等
原生的js和ajax
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Ajaxservlet
*/
@WebServlet(name="Ajaxservlet",urlPatterns="/Ajaxservlet")
public class Ajaxservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//中文乱码处理
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取前端请求过来的参数,name
String name=request.getParameter("name");
System.out.println(name);
if(name!=null&&"admin".equals(name)){
response.getWriter().write("成功");
}else{
response.getWriter().write("失败");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/jquery-3.2.1.min.js" ></script> <script type="text/javascript"> function ceshi(){ //获取文本框的数据 var v = document.getElementById("uid").value //创建xml对象 var xmlHttp=new XMLHttpRequest(); //打开请求,第一个参数:提交方式,第二个参数:请求路径,第三个参数,是否异步 xmlHttp.open("Get","http://localhost:8080/jquery-chapter6-ajax/Ajax.jsp?name="+v,true); //设置回调函数 xmlHttp.onreadystatechange = function(){ //判断状态 if(xmlHttp.readyState==4&&xmlHttp.status==200){ //成功之后获取服务端响应回来的数据 //var txt = xmlHttp.responseText; alert(xmlHttp.responseText) } } //发送请求 xmlHttp.send(null) } </script> </head> <body> <input id="uid" /> <button onclick="ceshi()">发送ajax请求到后台交互</button> </body> </html>
jquery的ajax
判断账号密码输入正确 错误
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/jquery-3.2.1.min.js" ></script> <script type="text/javascript"> $(function(){ $("button").click(function(){ //获取输入框的值 var name=$("#uid").val(); var pwd=$("#pid").val(); //jquery-ajax $.ajax({ async:true,//表示请求是否异步处理。默认是 true。 cache:false,//表示浏览器是否缓存被请求页面。默认是 true。 data:'uname='+name+'&pname='+pwd,//规定要发送到服务器的数据。 dataType:'text',//预期的服务器响应的数据类型。 type:'post',//请求方式,默认:get url:'demo1Servlet',//请求路径 success:function(data){ //请求成功后的回调函数 data时服务端的响应数据,形参名(自定义) alert(data); }, //请求失败后的回调函数 error:function(){ alert('ajax请求失败'); }, //请求完成后的回调函数,无论成功还是失败都回调 complete:function(){ alert('ajax请求完成'); } }) }) }) </script> </head> <body> <form> 账号:<input id="uid"/><br/> 密码:<input id="pid"/><br/> </form> <button>发送ajax请求</button> </body> </html>
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="Demo1Servlet",urlPatterns="/demo1Servlet")
public class Demo1Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//中文乱码处理
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取请求参数
String uname=request.getParameter("uname");
String pname=request.getParameter("pname");
System.out.println(uname+pname);
//模拟数据库的验证
if("zhangsan".equals(uname)&&"123456".equals(pname)){
response.getWriter().write("正确");
}else{
response.getWriter().write("错误");
}
}
}
简洁版ajax 取uname pname 必须和后台取页面 相同 .serialize()
$.ajax({
type:'post',//请求方式,默认:get
url:'demo1Servlet',//请求路径
data:$("#myform").serialize(),
success:function(data){ //请求成功后的回调函数 data时服务端的响应数据,形参名(自定义)
alert(data);
}
})
家庭作业:::::::前端,通过jquery ajax请求servlet,获取到json字符串数据,然后在前端进行解析,展示到页面中(自行百度)
在后台 取到json数据 展示到前台表格里 需要在里面设置
response.setContentType("application/json;charset=utf-8");
具体前后台代码如下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <style type="text/css"> table{ width: 480px; height: 200px; border-collapse: collapse; } table tr th,td{ border-collapse: collapse; border: 1px solid darkgoldenrod; text-align: center; } table td{ width:160px; height: 50px; } </style> <script type="text/javascript" src="js/jquery-3.2.1.min.js" ></script> <script type="text/javascript"> $(document).ready(function(){ //发送ajax请求 $.ajax({ type:"post", url:"homeworkServlet", success:function(data){ //把响应的数据转为json对象 //var u= JSON.parse(data); var u=data; for(var i=0;i<u.length;i++){ var tr= "<tr>"; tr+="<td>"+u[i].name+"</td>"; tr+="<td>"+u[i].sex+"</td>"; tr+="<td>"+u[i].age+"</td>"; tr+="</tr>"; $("table").append($(tr)); } } }) }) </script> </head> <body> <table border="1px" id="tab"> <tr> <td>姓名</td> <td>性别</td> <td>年龄</td> </tr> </table> </body> </html>
import java.io.IOException; import java.util.ArrayList; import java.util.List; 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 com.google.gson.Gson; @WebServlet(name="HomeworkServlet",urlPatterns="/homeworkServlet") public class HomeworkServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //中文乱码处理 request.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=utf-8"); //获取请求参数 Demo demo=new Demo(); List<User> list=demo.getinfo(); //创建gson对象 Gson gson = new Gson(); String json = gson.toJson(list); response.getWriter().write(json); } }
import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array; public class Demo { public static List<User> getinfo(){ List<User> list = new ArrayList<>(); for(int i=1;i<=5;i++){ User u = new User(i, "张三"+i,"男",16); list.add(u); Gson gson = new Gson(); String json = gson.toJson(list); } return list; } public static void main(String[] args) { List<User> list=getinfo(); //把list集合转为json字符串 //创建gson对象 Gson gson = new Gson(); String json = gson.toJson(list); System.out.println(json); //家庭作业 //前端,通过jquery ajax请求servlet,获取到json字符串数据,然后在前端进行解析,展示到页面中(自行百度) } } class User{ private int id; private String name; private String sex; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(int id, String name, String sex, int age) { super(); this.id = id; this.name = name; this.sex = sex; this.age = age; } }
jquery.post(提交方法)
$.post('demo3Servlet',{uname:uname,pname:pname},function(data){
alert(data);
})
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="Demo3Servlet",urlPatterns="/demo3Servlet")
public class Demo3Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//中文乱码处理
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取请求参数
String uname=request.getParameter("uname");
String pname=request.getParameter("pname");
System.out.println(uname+pname);
//模拟数据库的验证
if("zhangsan".equals(uname)&&"123456".equals(pname)){
response.getWriter().write("正确");
}else{
response.getWriter().write("错误");
}
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/jquery-3.2.1.min.js" ></script> <script type="text/javascript"> $(function() { $("button").click(function(){ //第一个参数 请求路径 //第二个参数 请求参数,格式,键值对 //第三个就是回调函数,函数data就是服务的相应的数据 var uname=$("#uid").val(); var pname=$("#pid").val(); $.post('demo3Servlet',{uname:uname,pname:pname},function(data){ alert(data); }) }) }) </script> </head> <body> <form id="myform"> 账号:<input id="uid" name="uname"/><br/> 密码:<input id="pid"/ name="pname"><br/> </form> <button>发送ajax请求</button> </body> </html>
jquery.getJSON()方法
$.getJSON('homeworkServlet',{},function(data){ //把响应的数据转为json对象 //var u= JSON.parse(data); var u=data; for(var i=0;i<u.length;i++){ var tr= "<tr>"; tr+="<td>"+u[i].name+"</td>"; tr+="<td>"+u[i].sex+"</td>"; tr+="<td>"+u[i].age+"</td>"; tr+="</tr>"; $("table").append($(tr)); } })