ajax 取值 返回map_springboot|前端发ajax请求到后台Controller及常见的坑
前端發(fā)ajax請求
這塊是web的基礎(chǔ),發(fā)web請求大概需要以下幾步1.引用web相關(guān)的依賴2.前端頁面引入jquery.js3.編寫ajax請求4.編寫對應(yīng)的Controller
引入web相關(guān)的依賴
前端的模板選用的是thymeleaf
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'implementation 'org.springframework.boot:spring-boot-starter-web'引入jquery
jquery可以通過本地的方式引入,也可以通過cdn的方式引入本地引入:先下載jquery.js到static/js目錄html頁面head中添加:
<head> <meta charset="UTF-8"> <title>Titletitle> <script src="/static/js/jquery-3.4.1.min.js">script>head>如果是CDN話,則不用下載jquery , 直接在head中引入
<head> <meta charset="UTF-8"> <title>Titletitle> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js">script>head>編寫ajax請求
參考文檔:https://api.jquery.com/jQuery.ajax/這里只展示一些常用的參數(shù)
$.ajax({ url:'/test/testAjax1', type:'get', async:false, contentType:'application/json', dataType:'json', success:function (data) { console.log(data) } })url:請求后臺的urltype:標(biāo)明是get還是post請求async:是異步的還是同步的,這里有個坑,有時候下拉框用ajax去請求數(shù)據(jù),這里默認(rèn)是異步的,結(jié)果數(shù)據(jù)還沒回來,下拉框就開始渲染,然后發(fā)現(xiàn)下拉沒有數(shù)據(jù)contentType: 前端的參數(shù)格式dataType:接口返回的數(shù)據(jù)的格式,一般來說,經(jīng)常不寫,讓系統(tǒng)自己去判定這里ContentType的值一般來說有兩種取值, 默認(rèn)是application/x-www-form-urlencoded; charset=UTF-8在實(shí)際開發(fā)中,經(jīng)常會改成如上的application/json這里改了之后,Controller中也要對應(yīng)著改入?yún)⒎绞?詳情可參考這篇DEMO:springboot|Controller接收處理GET,POST請求入?yún)ttps://www.javastudy.cloud/articles/2019/11/03/1572752115551.html
Controller接收請求
/** * @Author https://www.javastudy.cloud * @CreateTime 2019/11/8 **/@RestControllerpublic class TestController { @RequestMapping("test/testAjax1") public Map testAjax1(){ Mapmap = new HashMap<>(); map.put("aaa","bbb"); return map; } }結(jié)果輸出
DEMO總評
ajax請求是web開發(fā)中的第一步,我們可以按Http請求來理解他, 有相應(yīng)的header,有相關(guān)的各種type , 其中最麻煩的是要和后端Controller的參數(shù)對應(yīng)關(guān)系,稍不留神對應(yīng)錯了后端就收不了參數(shù),或者值沒法返回,要多看文檔,注意默認(rèn)值.
可添加小刀微信獲取源碼
往期熱文springboot|springboot配置Filter過濾器springboot|springboot配置攔截器docker|docker 安裝zookeeperjava基礎(chǔ)|自定義java線程池你點(diǎn)在看的樣子真好看:)~總結(jié)
以上是生活随笔為你收集整理的ajax 取值 返回map_springboot|前端发ajax请求到后台Controller及常见的坑的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang检查tcp是否可用_宕机处理
- 下一篇: 判断均匀平面波的极化形式_测瑞通|怎样判