Ajax
什么是ajax
一种异步无刷新请求
可以不用刷新网页就能更新数据的一种技术
主要参数
$.ajax(...) 部分参数: url:请求地址 type:请求方式,GET、POST(1.9.0之后用method) headers:请求头 data:要发送的数据 contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8") async:是否异步 timeout:设置请求超时时间(毫秒) beforeSend:发送请求前执行的函数(全局) complete:完成之后执行的回调函数(全局) success:成功之后执行的回调函数(全局) error:失败之后执行的回调函数(全局) accepts:通过请求头发送给服务器,告诉服务器当前客户端可接受的数据类型 dataType:将服务器端返回的数据转换成指定类型 "xml": 将服务器端返回的内容转换成xml格式 "text": 将服务器端返回的内容转换成普通文本格式 "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。 "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式 "json": 将服务器端返回的内容转换成相应的JavaScript对象 "jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数
我们主要掌握三个参数就可以了
1.url:要处理的地址
2.data:要传输的数据
3.success:成功后的函数function(data)这里面的data是后端传过来的函数
导入jQuery
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
编写实现判断用户名和密码是否正确
controller
@RequestMapping("/a3") public String a3(String name,String pwd){ String msg=""; if(name!=null){ if("admin".equals(name)){ msg="ok"; }else{ msg="ERROR"; } } if(pwd!=null){ if("123123".equals(pwd)){ msg="ok"; }else{ msg="ERROR"; } } System.out.println(msg); return msg;//类上用了RestController,这里直接返回JSON字符串 }
log.jsp
<%-- Created by IntelliJ IDEA. User: make Date: 2022/2/13 Time: 21:30 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="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script> <script> function a1(){ $.post({ url:"${pageContext.request.contextPath}/a3", data:{"name":$("#name").val()}, success:function (data){ if(data.toString()=='ok'){ $("#userinfo").css("color","green"); }else{ $("#userinfo").css("color","red"); }$("#userinfo").html(data) } }); } function a2(){ $.post({ url:"${pageContext.request.contextPath}/a3", data:{"pwd":$("#pwd").val()}, success:function (data){ if(data.toString()=='ok'){ $("#pwdinfo").css("color","green"); }else{ $("#pwdinfo").css("color","red"); }$("#pwdinfo").html(data) } }); console.log($("#pwd").val()); } </script> </head> <body> <p> name:<input type="text" id="name" onblur="a1()"/> <span id="userinfo"></span> </p> <p> pwd:<input type="text" id="pwd" onblur="a2()"/> <span id="pwdinfo"></span> </p> </body> </html>
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术