前后端通讯方式

一、Ajax

前端使用 axios 库与服务端通信。axios 返回的是 promise 对象。

示例(使用 es6语法):

axios.get(url)
.then(response => response.data)
.then(json => {

  // 处理后台传回来的json对象

});

文档:https://github.com/mzabriskie/axios

中文文档:http://www.kancloud.cn/yunye/axios/234845

二、GET 请求

用作数据查询接口。

参数可以直接写在url里,也可以如下表示:

axios.get(url, {
    params: {
      ID: '123'
    }
  })

三、POST 请求

用作数据的新增,提交接口。

使用两种提交方式。提交的内容为 js 对象,比如 data: {name:'abc', age:18}

方式一:application/x-www-form-urlencoded

axios.post(url, qs.stringify(data))
.then(response => response.data)
.then(json => {

  // 处理后台传回来的json对象

});

注:qs库用来将 js 对象转为 key=value&key2=value2形式。

Spring MVC后台使用

(@RequestParam("name") String name, @RequestParam("age") Integer age)

或包装对象 (User user)来接收数据 

方式二:application/json

axios.post(url, data)

.then(response => response.data)
.then(json => {

  // 处理后台传回来的json对象

});

Spring MVC后台使用

(@RequestBody Map map) 获取对象结构
(@RequestBody List list) 获取列表结构

也可以用对象来接收相同结构的 json 数据

四、PUT请求

用作数据的更新接口。使用方式同POST。

五、DELETE请求

用作数据的删除接口。

axios调用方式如下:

  axios.delete(url, {data: data})

由于OA集成环境下的WebSEAL会拦截带body的DELETE请求,目前WebSEAL暂未解决。

因此改为采用将参数放在path中,或将参数放在query string中。

猜你喜欢

转载自blog.csdn.net/qq_34117825/article/details/80435373