本系列主要講解前後端數據的傳輸(HTML + SpringBoot)
- form 提交
- Ajax 異步傳輸
- websocket 提交
本文主要講解Ajax
基本原理的大話我就不說了,直接google。
強調一點Ajax
主要是通過瀏覽器提供的XMLHttpRequest
與後臺進行交互。
由於原生JavaScript
語言過於冗雜,本文采用JQuery
進行編寫。如果想使用原生JavaScript
,可訪問 https://blog.csdn.net/qq_36140085/article/details/81567592
HTML 傳遞接受數據
Jquery Ajax 方法
$.ajax({
url:"http://www.microsoft.com", //請求的url地址
dataType:"json", //返回格式爲json
async:true,//請求是否異步,默認爲異步,這也是ajax重要特性
data:{"id":"value"}, //參數值
type:"GET", //請求方式
beforeSend:function(){
//請求前的處理
},
success:function(req){
//請求成功時處理
},
complete:function(){
//請求完成的處理
},
error:function(){
//請求出錯處理
}
});
//此內容來自[https://www.cnblogs.com/yebingtang/p/11049948.html]
首先在靜態文件夾中建立Ajax.html
,創建click
點擊,在其中執行Ajax
操作。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax TEST</title>
</head>
<body>
<p>Ajax</p>
<h1 id="10">Change</h1>
<button id="change" type="button">click</button>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function () {
$("#change").on('click',function (event) {
$.ajax({
url: "/getJson",
dataType: "json",
data: {"id": 1},
type: "POST",
beforeSend:function(){
$("p").html("<P>sssssssssssss</P>");
},
success:function(result){
$("#10").text(result['1']);
}
}
)
})
})
</script>
</html>
我們會將
data : {"id":1}
傳到
url : "/getJson"
這個網址。
後端接收數據
建立Controller
@RestController
public class AjaxController {
@RequestMapping(value="/getJson", method = {RequestMethod.GET, RequestMethod.POST})
public Map<String, Object> login(@RequestParam Map<String, Object> params){
System.out.printf("%s", params.get("id"));
Map<String,String> res = new HashMap<String,String>();
res.put("1","222");
return res;
}
}
@RestController
表明返回的是Json
數據,不是視圖。
此處以@RequestParam Map<String, Object> params
的形式接受前端的Json
數據。
click前
click後