前后端交互的過程我覺得不管是前端還是后端都需要了解一點。
一、首先是前端發送請求:(我只了解了一點 ajax)
1、服務器端大多數情況下會以 JSON 對象作為響應數據的格式。
2、無論是請求參數還是響應內容、如果是對象類型,最終都會被轉換為對象字符串進行傳輸。
3、將 JSON 字符串轉換為 JSON 對象 JSON.parse(JSON_String),將 JSON 對象轉換為 JSON 字符串 JSON.stringify()。
4、兩種請求參數格式 1、'application/x-www-form-urlencoded',2、'application/json'。
第一種格式為:'name=apple&age=20',第二種格式為:{name : 'apple',age : 20}。
5、get 請求方式不能提交 json 對象數據格式。
6、Ajax 錯誤處理
Ⅰ、網絡暢通,服務器端能接受到請求,服務器端返回的結果不是預期結果。(判斷服務器的返回的狀態碼,分別進行處理)
Ⅱ、網絡暢通,服務器沒有接受到請求,返回 404 狀態碼。(請求地址錯誤)
Ⅲ、網絡暢通,服務器端能接受到請求,服務器返回 500 狀態碼。(服務器端錯誤)
Ⅳ、網絡中斷,請求無法發送到服務器。
7、jQuery 中的 ajax 方法
$.ajax({ type:'get', // type:'post' url:'http://localhost:8080/login', data:{uname:'apple',pwd:'123456'}, // data:'uname=apple&pwd=123456' contentType:'application/x-www-form-urlencoded, // application/json beforeSend:function(){}, success:function(response){}, error:function(response){} });
8、script 中調用 ajax
<script> $('#btn').on('click',function(){ $.ajax({}) }); </script>
9、serialize 方法:將表單重點數據自動拼接成字符串類型的參數
var params = $('#form').serialize() // 'uname=apple&pwd=123456'
10、$.get()、$.post() 方法:
$.get('/login','uname=apple&pwd=123456',function (response){}) $.post('/login','uname=apple&pwd=123456',function(response){})
二、其次后端返回數據的函數是類似於這樣的:
private ObjectMapper objectMapper = new ObjectMapper(); (HttpServletRequest request, HttpServletResponse response)->{ Map<String,Object> data = new HashMap<>(); data.put("result", "success"); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(objectMapper.writeValueAsString(data)); }
三、前端接受數據
success:function(response){ console.log(response.result) }
四、通過 ajax 的 success() 函數接受返回的數據會導致頁面不跳轉的問題
window.location.href='/index'
五、Spring 控制器獲取參數
1、@RequestParam 方式:
@PostMapping("/myInfo") public String showInfo(@RequestParam("name") String name){ Reader reader = repository.findReaderByName(name); return "infomation"; }
2、@RequestParam 方式,帶默認值
@PostMapping("/myInfo") public String showInfo((value="name",defaultValue="anonymous") String name){ Reader reader = repository.findReaderByName(name); return "infomation"; }
3、{} 占位符方式,路徑變量
@PostMapping("/{name}") // 若方法的參數名和占位符名稱相同,則可以省略@PathVariable 中的 value屬性 public String showInfo(@PathVariable("name") String name){ Reader reader = repository.findReaderByName(name); return "infomation" }
六、后台通過 Model 傳遞數據和前端讀取 Model 傳過來的數據(只知道如何傳,不知道如何讀)
七、以上內容僅是本人剛學的筆記,如有錯誤,歡迎指正!希望大佬能告知第六部分內容,謝謝!