前端发ajax请求
这块是web的基础,发web请求大概需要以下几步1.引用web相关的依赖2.前端页面引入jquery.js3.编写ajax请求4.编写对应的Controller
引入web相关的依赖
前端的模板选用的是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/这里只展示一些常用的参数
$.ajax({ url:'/test/testAjax1', type:'get', async:false, contentType:'application/json', dataType:'json', success:function (data) { console.log(data) } })
url:请求后台的urltype:标明是get还是post请求async:是异步的还是同步的,这里有个坑,有时候下拉框用ajax去请求数据,这里默认是异步的,结果数据还没回来,下拉框就开始渲染,然后发现下拉没有数据contentType: 前端的参数格式dataType:接口返回的数据的格式,一般来说,经常不写,让系统自己去判定这里ContentType的值一般来说有两种取值, 默认是application/x-www-form-urlencoded; charset=UTF-8
在实际开发中,经常会改成如上的application/json
这里改了之后,Controller中也要对应着改入参方式,详情可参考这篇DEMO:springboot|Controller接收处理GET,POST请求入参https://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; } }
结果输出
DEMO总评
ajax请求是web开发中的第一步,我们可以按Http请求来理解他, 有相应的header,有相关的各种type , 其中最麻烦的是要和后端Controller的参数对应关系,稍不留神对应错了后端就收不了参数,或者值没法返回,要多看文档,注意默认值.
可添加小刀微信获取源码
![7b4b95ae44f44f838d16a9a62624bdd2.png](https://img-blog.csdnimg.cn/img_convert/7b4b95ae44f44f838d16a9a62624bdd2.png)