使用Ajax技术网页应用能够快速的将增量更新在用户界面上,而不需要重新加载整个页面,这使得程序能够更快的回应用户的操作。
1.1 Ajax特点局部刷新,异步访问。
- 同步请求:浏览器发起请求到服务器,如果服务器没有响应,用户则无法获取页面数据,处于等待状态,不可以做其他操作。
- 异步请求:异步请求时,浏览器可以进行其他的操作,当ajax数据获取之后,信息在页面局部刷新,可以理解为多线程的操作方式。
Ajax可以异步原理:中间有Ajax引擎
回调函数:服务器返回数据,通过回调函数通知用户。
注解方式
@RestController
@RequestMapping("/axios")
@CrossOrigin //解决跨域问题
public class AxiosController {
3. 前后端调用案例
3.1 前后端调用—入门案例
前端JS
Axios demo
编辑AxiosController
package com.huo.demo1_Axios.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/axios")
@CrossOrigin //解决跨域问题
public class AxiosController {
@GetMapping("/findStr")
public String findStr(){
return "好的好的哈";
}
}
结果:
编辑页面JS
let url2="http://localhost:8080/axios/getUserById?id=100";
axios.get(url2)
.then(function(promise){
console.log(promise.data)
})
编辑AxiosController
@GetMapping("/getUserById")
public String getUserById(Integer id){
return "id:"+id;
}
结果:
axios.defaults.baseURL="http://localhost:8080";
let url1="/axios/findStr"
axios.get(url1)
.then(function(promise){
console.log(promise.data)
})
3.4 前后端调用—对象传参
编辑页面JS
//对象参数传递写法 利用API自动拼接参数
let user={id: 100,name: "tomcat"};
axios.get("/axios/findUser",{params: user})
.then(function(promise){
console.log(promise.data)
})
编辑AxiosController
@GetMapping("/findUser")
public User getFindUser(User user){
return user;
}
返回User对象
ResultFul的结构不区分请求类型,任意请求类型都可以通过ResultFul的结构发送数据。
编辑页面JS
//RestFul 结构 模板字符串写法
let rest={id:100,name:"tomcat",age:99}
axios.get(`/axios/result/${rest.id}/${rest.name}/${rest.age}`)
.then(function(promise){
console.log(promise.data)
})
编辑AxiosController
//对象方式接收参数
@GetMapping("/result/{id}/{name}/{age}")
public User result(User user){
return user;
}
//单个属性值接收的方式使用 @PathVariable 注解
返回user对象
编辑页面JS
ajax post 请求
编辑AxiosController
@PostMapping("/saveUser")
public User saveUser(@RequestBody User user){
return user;
}
返回User对象
说明:前端代码传递的JS对象,而后端使用的是java对象,2种对象没有办法直接转化,需要转化为JSON进行传递,axios使用post请求时,自动将JS对象解析为JSON串。
注:@RequestBody 将JSON转化为Java对象
@ResponseBody 将Java对象转化为JSON串
浏览器的网址与Ajax请求的网址必须满足如下的要求:
协议://域名:端口号必须相同
如果满足要求则是同域访问,如果不满足要求则是跨域访问。
业务中经常遇到A的数据来源B,B的数据来源C。以此类推,则形成了Ajax嵌套的结构。
axios函数方式
箭头函数写法



