什么是Ajax?
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。无需重新加载整个网页的情况下,能够更新部分网页。不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。
-
传统的网页(即不用ajax技术的网页),想要更新内容或者提交一个表单,都需要重新加载整个网页。
-
使用ajax技术的网页,通过在后台服务器进行少量的数据交换,就可以实现异步局部更新。
使用iframe伪造Ajax:
<script type="text/javascript">
window.onload = function f(){
var nowDate = new Date();
document.getElementById("currentTime").innerText = nowDate.getTime();
}
function loadPage() {
var targetURL = document.getElementById("url").value;
console.log(targetURL);
document.getElementById("iframePosition").src = targetURL;
}
</script>
<div>
当前时间:
<span id="currentTime"></span>
</div>
<div>
请输入地址:
<input type="text" id="url">
<input type="button" value="提交" onclick="loadPage()">
</div>
<div>
刚才输入的地址,将在以下小框中加载: <br>
<iframe style="width: 300px; height: 200px" id="iframePosition">
</iframe>
</div>
显示结果:
结合SpringMVC使用Ajax
1、当用户名输入框失去焦点的时候,向后端传值。如果输入值为admin,返回true。否则返回false
前端:
<%@ 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>
</head>
<body>
<script type="text/javascript">
function a1(){
//所有参数:
//url:待载入页面的URL地址,Json
//data:待发送 key/value 参数
//success:载入成功时回调函数
//data:封装了服务器返回的数据
//status:状态
//ajax默认是get请求
$.ajax({
url:"${pageContext.request.contextPath}/ajax/a1",
data:{"name":$("#txtName").val()},
success: function (data,status) {
console.log(data);
}
});
}
</script>
用户名:
<input type="text" id="txtName" onblur="a1()"/>
</body>
</html>
后端:
@Controller
@RequestMapping("/ajax")
public class AjaxController {
@RequestMapping("/a1")
public void ajax(String name, HttpServletResponse response) throws IOException {
if("admin".equals(name)){
response.getWriter().print("true");
}else {
response.getWriter().print("false");
}
}
}
显示结果:
2、点击“获取数据”按钮,将后端的List<User>,在前端显示为一个表格
User类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
前端:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<input type="button" id="btn" value="获取数据"/>
<table width="200px">
<tr>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<tbody id="content">
</tbody>
</table>
<script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
<script>
$(function(){
$("#btn").click(function(){
$.post("${pageContext.request.contextPath}/ajax/a2", function(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")
@ResponseBody
public List<User> ajax2() {
List<User> userList = new ArrayList<User>();
User user1 = new User("张三",3,"男");
User user2 = new User("李四",4,"男");
User user3 = new User("王五",5,"男");
userList.add(user1);
userList.add(user2);
userList.add(user3);
return userList; //由于加了@ResponseBody注解,他会返回一个字符串
}
显示结果:
3、输入用户名和密码,当输入框失去焦点后,向后端传输入值。如果用户名输入值为admin,提示ok,否则提示用户名有误。如果密码输入值为123456,提示ok,否则提示密码输入有误。
前端:
<%@ 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:"${pageContex.request.contextPath}/ajax/a3",
data:{"name":$("#name").val()},
success: function(data){
$("#userInfo").html(data);
if(data.toString() == "ok"){ //信息核对成功
$("#userInfo").css("color","green");
}else{
$("#userInfo").css("color","red");
}
}
})
}
function a2(){
$.post({
url:"${pageContex.request.contextPath}/ajax/a3",
data:{"pwd":$("#pwd").val()},
success: function(data){
$("#pwdInfo").html(data);
if(data.toString() == "ok"){ //信息核对成功
$("#pwdInfo").css("color","green");
}else{
$("#pwdInfo").css("color","red");
}
}
})
}
</script>
</head>
<body>
<p>
用户名:
<input type="text" id="name" onblur="a1()"/>
<span id="userInfo"></span>
</p>
<p>
密码:
<input type="text" id="pwd" onblur="a2()"/>
<span id="pwdInfo"></span>
</p>
</body>
</html>
后端:
@RequestMapping("/a3")
@ResponseBody
public String ajax3(String name, String pwd) {
String msg = "";
if(name != null) {
if ("admin".equals(name)) {
msg = "ok";
} else {
msg = "用户名有误";
}
}
if(pwd != null) {
if ("123456".equals(pwd)) {
msg = "ok";
} else {
msg = "密码输入有误";
}
}
return msg;
}
显示结果: