导学
Jquery在此处不做讲解,各位同学各自复习,主要需要学习的是通过Ajax实现前后台的联动。


Ajax入门
Asynchronous JavaScript And XML (异步的JavaScript和XML),Ajax可以在不刷新页面的前提下,进行页面局部更新,Ajax不是新的技术,Ajax并不是W3C的标准。
在过去,我们在网页中刷新页面内容,需要重新从服务器获取新的页面。
Ajax的出现,揭开了无刷新更新页面的新时代。
Ajax优势
- 优秀的用户体验:Ajax最大的有点是能在不刷新整个页面的前提下更新数据,这使得Web应用能迅速的回应用户的操作。
- 提高Web程序的性能:在传统模式中,数据提交是通过表单来实现的,而数据的获取则需要全页面刷新来获取整页内容。Ajax可以不刷新整个页面,按需提交数据给服务器,并接收服务器返回,然后通过dom操作,按需刷新页面的一部分。
- 减轻服务器和带宽的负担:Ajax的工作原理相当于在用户和服务器之间加了一个中间层,使用户操作与服务器响应异步化。把传统方式下的一些服务器负担的工作转移到了客户端。
jquery中的ajax
$ajax()方法是jQuery最底层的Ajax实现。
结构:$.ajax(options)
options参数是一个对象:
| options参数名称 | 说明 | |||||
|---|---|---|---|---|---|---|
| url | 发送请求的地址 | |||||
| type | 请求方式(`get | post`) | ||||
| timeout | 请求超时时间(毫秒) | |||||
| data | 发送到服务器的数据 | |||||
| datatype | 预期服务器返回的数据类型(`text | json | xml | html | jsonp | script`) |
| success | 请求成功后调用的回调函数 | |||||
| error | 请求失败后调用的回调函数 |

public class News {private String title;private String date;private String source;private String content;public News() {}public News(String title, String date, String source, String content) {super();this.title = title;this.date = date;this.source = source;this.content = content;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getDate() {return date;}public void setDate(String date) {this.date = date;}public String getSource() {return source;}public void setSource(String source) {this.source = source;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}}
@WebServlet("/news_list")public class NewsListServlet extends HttpServlet {private static final long serialVersionUID = 1L;public NewsListServlet() {super();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String type = request.getParameter("t");List list = new ArrayList();if(type != null && type.equals("pypl")) {list.add(new News("PYPL:2018年5月份全球编程语言排行榜" , "2018-5-1" , "PYPL" , "..."));list.add(new News("PYPL:2018年6月份全球编程语言排行榜" , "2018-6-1" , "PYPL" , "..."));list.add(new News("PYPL:2018年7月份全球编程语言排行榜" , "2018-7-1" , "PYPL" , "..."));list.add(new News("PYPL:2018年8月份全球编程语言排行榜" , "2018-8-1" , "PYPL" , "..."));}else if(type == null || type.equals("tiobe")) {list.add(new News("TIOBE:2018年5月份全球编程语言排行榜" , "2018-5-1" , "TIOBE" , "..."));list.add(new News("TIOBE:2018年6月份全球编程语言排行榜" , "2018-6-1" , "TIOBE" , "..."));list.add(new News("TIOBE:2018年7月份全球编程语言排行榜" , "2018-7-1" , "TIOBE" , "..."));list.add(new News("TIOBE:2018年8月份全球编程语言排行榜" , "2018-8-1" , "TIOBE" , "..."));}String json = JSON.toJSONString(list);System.out.println(json);response.setContentType("text/html;charset=UTF-8");response.getWriter().println(json);}}
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><script type="text/javascript" src="js/jquery-3.3.1.js"></script><script type="text/javascript">$(function(){$.ajax({"url" : "/ajax/news_list","type" : "get" ,"data" : {"t":"pypl" , "abc":"123" , "uu":"777"},//"data" : "t=pypl&abc=123&uu=777" ,"dataType" : "json" ,"success" : function(json){console.log(json);for(var i = 0 ; i < json.length ; i++){$("#container").append("<h1>" + json[i].title + "</h1>");}},"error" : function(xmlhttp , errorText){console.log(xmlhttp);console.log(errorText);if(xmlhttp.status == "405"){alert("无效的请求方式");}else if(xmlhttp.status == "404"){alert("未找到URL资源");}else if(xmlhttp.status == "500"){alert("服务器内部错误,请联系管理员");}else{alert("产生异常,请联系管理员");}}})})</script></head><body><div id="container"></div></body></html>
案例:二级联动菜单
public class Channel {private String code;private String name;public Channel() {}public Channel(String code, String name) {super();this.code = code;this.name = name;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
@WebServlet("/channel")public class ChannelServlet extends HttpServlet {private static final long serialVersionUID = 1L;public ChannelServlet() {super();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String level = request.getParameter("level");String parent = request.getParameter("parent");List chlist = new ArrayList();if(level.equals("1")) {chlist.add(new Channel("ai" , "前沿/区块链/人工智能"));chlist.add(new Channel("web" , "前端/小程序/JS"));}else if(level.equals("2")) {if(parent.equals("ai")) {chlist.add(new Channel("micro" , "微服务"));chlist.add(new Channel("blockchain" , "区块链"));chlist.add(new Channel("other" , "..."));}else if(parent.equals("web")){chlist.add(new Channel("html" , "HTML"));chlist.add(new Channel("css" , "CSS"));chlist.add(new Channel("other" , "..."));}}String json = JSON.toJSONString(chlist);response.setContentType("text/html;charset=utf-8");response.getWriter().println(json);}}
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><script type="text/javascript" src="js/jquery-3.3.1.js"></script><script type="text/javascript">$(function(){$.ajax({"url" : "/ajax/channel","data" : {"level" : "1"},"type" : "get" ,"dataType" : "json" ,"success" : function(json){console.log(json);for(var i = 0 ; i < json.length ; i++){var ch = json[i];$("#lv1").append("<option value='" + ch.code + "'>" + ch.name + "</option>")}}})})$(function(){$("#lv1").on("change" , function(){var parent = $(this).val();console.log(parent);$.ajax({"url" : "/ajax/channel" ,"data" : {"level" : "2" , "parent" : parent},"dataType" : "json" ,"type" : "get" ,"success" : function(json){console.log(json);//移除所有lv2下的原始option选项$("#lv2>option").remove();for(var i = 0 ; i < json.length ; i++){var ch = json[i];$("#lv2").append("<option value='" + ch.code +"'>" + ch.name + "</option>")}}})})})</script></head><body><select id="lv1" style="width:200px;height:30px"><option selected="selected">请选择</option></select><select id="lv2" style="width:200px;height:30px"></select></body></html>
