生活随笔
收集整理的這篇文章主要介紹了
使用jQuery与后端进行数据传输代码示例
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.編寫(xiě)前端頁(yè)面 + Ajax請(qǐng)求
-
表單域 form (三大部分:form、表單域、提交按鈕 type="submit"。 每個(gè)input需要有名字!否則無(wú)法被serialize()添加進(jìn)數(shù)據(jù)中)
-
為submit添加on監(jiān)聽(tīng)事件。1.阻止默認(rèn)行為 2.通過(guò) form選擇器.serialize( )把表單的所有數(shù)據(jù)添加進(jìn)data中(務(wù)必每個(gè)input都有個(gè)name屬性)
-
通過(guò)jquery發(fā)送ajax請(qǐng)求!規(guī)定好url、type、method、data、success等等
-
特別注意:若后端返回的是 @ResponseBody String 則 type=”text“ ; 若后端返回的是json,則type=”JSON“
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="js/jquery-3.4.1.js"></script><script>$(function(){$('form').on('submit',function(e){//Step1.阻止submit的默認(rèn)行為e.preventDefault();
?//Step2.獲取表單內(nèi)所有的數(shù)據(jù)【各個(gè)input 一定要有name屬性!】var str = $('form').serialize();
?//Step3.發(fā)送Ajax請(qǐng)求$.ajax({url: "http://localhost:9090/test", //后端地址type: "text", //提交方式method: "GET",data: str,dataType: "text", //規(guī)定請(qǐng)求成功后返回的數(shù)據(jù)success: function (data) {//請(qǐng)求成功之后進(jìn)入該方法,data為成功后返回的數(shù)據(jù)console.log(data);console.log("發(fā)送ajax成功");},error: function (errorMsg) {console.log(errorMsg);console.log("發(fā)送ajax失敗");}});
?})})</script>
</head>
<body><form><input type="text" name="name" value="" placeholder="name"><input type="text" name="age" value="" placeholder="age"><button type="submit">submit</button></form>
</body>
</html>
2.編寫(xiě)后端響應(yīng)(只說(shuō)明數(shù)據(jù)交換部分。詳細(xì)知識(shí)點(diǎn)請(qǐng)看后端的SpringMVC、Springboot 等筆記)
-
首先,需要解決跨域問(wèn)題。 在Controller類(lèi)上添加一個(gè) @CrossOrigin 即可解決跨域問(wèn)題
-
添加 @RequestMapping() 作為前端ajax 發(fā)送url的地址
-
@ResponseBody 讓返回的String為text類(lèi)型 / 讓返回的對(duì)象自動(dòng)轉(zhuǎn)為json類(lèi)型
-
Controller內(nèi)的方法,需要使用 對(duì)象 作為參數(shù),接收來(lái)自前端的參數(shù)
package com.example.module1.controller;
?
?
import com.example.module1.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
?
?
@Controller
@CrossOrigin
public class TestController {
?
?
?@RequestMapping("/test")@ResponseBodypublic String test(User user){System.out.println(user);return "success";
?}
}
?
總結(jié)
以上是生活随笔為你收集整理的使用jQuery与后端进行数据传输代码示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。