SpringBoot技术升级 thymeleaf===>html+css+js+Ajax
我们的征程是星辰大海,而非人间烟尘
Ajax异步请求
客户端发出请求消息后,不等待服务器的响应结果,继续执行其他操作。
Ajax:即异步 JavaScript 和XML。Ajax是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,Ajax可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。而传统的网页(不使用 Ajax)如果需要更新内容,必需重载整个网页面。
插入一个博客:Ajax请求的五个步骤
任务:
-
书写后端请求
-
写前端页面
-
引入JqueryCDN的链接
http://libs.baidu.com/jquery/2.1.4/jquery.min.js
-
Ajax.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js" > </script> </head> <script> function getname() { $.ajax({ type:'post', url:'http://localhost:8088/springboot/test', contentType:'application/json', //添加 contentType:“application/json“之后,向后台发送数据的格式必须为json字符串 success:function (data){ console.log(data); var a = data.name; $('#name').text(a); } }) } </script> <body onload="getname()"> <h3>测试Ajax</h3> <h5 id="name">name</h5> </body> </html>
-
-
结果
跨域访问
假如把Ajax.html当做静态资源打开,就会出现下面的问题
解决跨域问题就是在controller层加上
@CrossOrigin
注解,允许跨域访问
前后端分离技术
解决了跨域问题,我们就可以把HTML文件当做静态资源打开,那么你就可以解决前后端分离,前端只需要完成页面的书写,绑定数据,后端完成接口,约定统一的格式来传递数据。
传递表单数据
- 后端代码
-
前端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js" ></script> <title>Document</title> </head> <script> function f1() { console.log("111"); console.log($('#fm').serialize()); $.ajax({ type:'post', url:'http://localhost:8088/springboot/test4', data: $('#fm').serialize(), success:function (res) { console.log(res); if (res.code == 0) window.location.href="success.html" else document.getElementById("name").innerHTML = res.msg; } }) } </script> <body> <h3>登陆</h3> <form id="fm" method="post" action="" onsubmit="return false"> 用户名:<input type="text" name="username"> <br><br> 密码:<input type="password" name="password"> <br><br> <input type="submit" onclick="f1()" value="登陆"> <input type="reset" value="重置"> </form> <div id="name"></div> </body> </html>
传递JSON提交数据
-
后端代码
-
前端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js" ></script> <title>Document</title> </head> <script> function f1() { $.ajax({ type:'post', url:'http://localhost:8088/springboot/test5', data: JSON.stringify({ 'username':$('#username').val(), 'password':$('#password').val() }), contentType:'application/json', success:function (res) { console.log(res); if (res.code == 0) window.location.href="success.html" else document.getElementById("name").innerHTML = res.msg; } }) } </script> <body> <h3>登陆</h3> 用户名:<input type="text" id="username"> <br><br> 密码:<input type="password" id="password"> <br><br> <input type="submit" onclick="f1()" value="登陆"> <input type="reset" value="重置"> <div id="name"></div> </body> </html>