Ajax:异步无刷新请求
Type为xhr请求
这就是Ajax
Jquery是一个库,库里面有js的大量函数(方法)
HTML + css:略懂 + js(超级熟练)
js:
函数:闭包()()
Bom:window事件 document
Dom:id,name,tag,create,remove
ES6: import require
AJAX就是将主动权交给了前端
实战1代码:
前端:
<%-- Created by IntelliJ IDEA. User: 邬松 Date: 2021/4/17 Time: 8:12 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <%-- <script src="${pageContext.request.contextPath}/statics/jquery-3.6.0.min.js"></script>--%> <script> function a1(){ $.post({ url:"${pageContext.request.contextPath}/a1", data:{'name':$("#txtName").val()}, success:function (data,status) { alert(data); alert(status); }, error:function (){ alert("请求失败!"); } }); } </script> </head> <body> <%--onblur:失去焦点触发事件--%> 用户名:<input type="text" id="txtName" οnblur="a1()"/> </body> </html>
后端
package com.kuang.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.IOException; //@RestController @Controller public class AjaxController { @RequestMapping("/helloya") public String test1(){ return "hello!"; } @RequestMapping("/a1") public void ajax1(String name , HttpServletResponse response) throws IOException { System.out.println("a1:param=>"+name); if ("admin".equals(name)){ response.getWriter().print("true"); }else{ response.getWriter().print("false"); } } }
测试结果:
实战2代码渲染数据
前端
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <input type="button" id="btn" value="获取数据"/> <table width="80%" align="center"> <tr> <td>姓名</td> <td>年龄</td> <td>性别</td> </tr> <tbody id="content"> </tbody> </table> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $(function () { $("#btn").click(function () { $.post("${pageContext.request.contextPath}/a2",function (data) { console.log(data) //将json字符串转换成json对象 data = JSON.parse(data); console.log("转换后------------") console.log(data) var html=""; for (var i = 0; i <data.length ; i++) { html+= "<tr>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].age + "</td>" + "<td>" + data[i].sex + "</td>" + "</tr>" } $("#content").html(html); }); }) }) </script> </body> </html>
后端
@RequestMapping("/a2") public String ajax2(){ List<User> list = new ArrayList<User>(); list.add(new User("秦疆1号",3,"男")); list.add(new User("秦疆2号",3,"男")); list.add(new User("秦疆3号",3,"男")); final String s = JSON.toJSONString(list); System.out.println(s); return s; //由于@RestController注解,将list转成json格式返回 }
结果
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/106050.html