写在前面
通常在开发结束后,新的项目或者重构项目难免会遇到请求接口方案选择的切换的场景。如果没有刻意的去记录,很容易搞混,于是我针对 js的ajax、vue-cli的axios 以及uni-app 的uni-request三种方案,分别记录了对应的get、post/put/delete 传递form、post/put/delete 传递数组三种常见的传递方式以及对应的前端和后台代码做了记录。9类请求全部亲测无误,由于方式太多,所以每种只记录一种,因此可能方案不是最佳,如果有更佳的方案欢迎在评论区补充。
一、 ajax
1. get
前端
$.ajax({
url: base_path + "/role/allowPermissions",
type: "get",
dataType: "json",
error:function(e){
layer.msg('数据加载失败,请稍后再试!', function () { time: 2000 });
},
success: function (data) {
...... //业务处理
}
})
后台
/**
* @param session
* @return JSONOObject
* @function 获取登录的管理员所属角色下的所有权限列表
*/
@RequiresPermissions("role:list")
@RequestMapping(value = "/allowPermissions", method = RequestMethod.GET)
public Object getAllowPermissions(HttpSession session) {
return roleService.getAllowPermissions(session);
}
2. post/put/delete 传递form
前端
$.ajax({
url: base_path + "/user/add",
type: "post",
dataType: "json",
data: {
REALUSERNAME: REALUSERNAME,
PHONENUM: PHONENUM,
......
},
success: function (data) {
// 完成验证后提交信息并关闭页面
layer.close(index);
},
error: function (e) {
layer.msg('数据请求失败,请稍后再试!', function () { time: 2000 });
}
})
后台
/**
* 添加人员
*/
@RequiresPermissions("user:handler")
@RequestMapping(value = "add",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
public JSONObject addEmployee(HttpSession session,TblEmployees tblEmployees){
...... //业务处理
}
3.post/put/delete 传递数组
前端
var ids = [];
ids.push("1");
ids.push("2");
$.ajax({
url: base_path + "/user/delete",
type: "post",
dataType: "json",
data: {
id: ids
},
error: function (e) {
layer.msg('数据加载失败,请稍后再试!', function () { time: 2000 });
},
success: function (data) {
...... //业务处理
}
})
后台
/**
* 批量删除人员信息
*/
@RequiresPermissions("user:handler")
@RequestMapping(value ="delete",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
@ResponseBody
public JSONObject deletePerson(HttpSession session,@RequestParam("id[]")List<String> ids) {
LAdmin ladmin = (LAdmin) session.getAttribute(GlobalVar.ADMIN);
String deletePerson = ladmin.getComments();
Map<String,Object> resultMap = userService.deletePerson(ids,deletePerson);
return JSONObject.parseObject(JSON.toJSONString(resultMap));
}
二、 axios
备注
全局注册(此为使用axios)
import axios from 'axios'
axios.defaults.baseURL = "http://127.0.0.1:9102/myProject"; //设置axios请求根路径
Vue.prototype.$axios = axios //全局注册,使用方法为:this.$axios
1. get
前端
let that = this;
this.$axios.get('/category/buildTree',{
params:{
id:tree.id
}
}).then(function (response) {
let data = response.data.result;
resolve(data);
})
.catch(function (error) {
console.log(error);
});
后台
/**
* 构建分类tree
* @param id
* @return
*/
@GetMapping("buildTree")
public Object buildTree(Integer id,String condition){
return categoryService.buildTree(id);
}
2. post/put/delete 传递form
前端
let that = this;
let param = new URLSearchParams();
param.append('pid', that.form.id);
param.append('name', that.form.name);
let url = that.form.imageUrl;
param.append('img', url);
this.$axios({
method:"POST",
url:'/category/add',
data: param
})
.then(function (response) {
that.$message.success('操作成功')
setTimeout(()=>{that.myReload();},1500)
})
.catch(function (error) {
console.log(error);
});
后台
@PostMapping("add")
public Object addCategory(HttpServletRequest request,String pid,String name,String img){
return categoryService.addCategory(request,pid,name,img);
}
3.post/put/delete 传递数组
前端
let that = this;
let ids = [];
ids.push(rows.id);
this.$axios({
method:"delete",
url:'/category/delete',
params: {
ids:ids
},
paramsSerializer: function(params) {
return qs.stringify(params, { arrayFormat: 'repeat' })
}
})
.then(function (response) {
that.$message.success('操作成功')
setTimeout(()=>{that.myReload();},1500)
})
.catch(function (error) {
console.log(error);
});
注意:此处需要引用qs,这是axios中自带的需要再当前vue文件中引用
</div>
</template>
<script>
const qs = require('qs');
export default {
inject:['myReload'],
data() {
return {
//添加自由选择父节点的分类配置
defaultProps: {
label: 'name',
isLeaf: 'leaf'
},
......
...
后台
/**
* 分类相关 删除分类节点
* @return
*/
@ApiOperation("删除商品分类")
@ApiImplicitParams({
@ApiImplicitParam(name = "ids[]", value = "删除的节点集合", required = false,allowMultiple=true, dataType = "String")
})
@DeleteMapping("delete")
public Object deleteCategory(HttpServletRequest request,String[] ids){
List list = Arrays.asList(ids);
return categoryService.deleteCategory(request,list);
}
三、 uni-app
1. get
前端
let that = this;
let id = that.addressData.id;
uni.request({
url: getApp().globalData.websiteUrl + '/location/check',
data:{
id:id
},
method:'GET',
success: (res) => {
if(res.data.code === 200){
...... //业务处理
}
}
});
后台
@GetMapping("check")
public Object checkLocation(ShopAddress shopAddress){
return locationService.checkLocation(shopAddress);
}
2. post/put/delete 传递form
前端
let that = this;
uni.request({
url: getApp().globalData.websiteUrl + '/location/update',
method: 'PUT',
data: {
id: data.id,
comment1: that.comment1.replace(/s*/g, ""),
comment2: that.comment2.replace(/s*/g, ""),
region: that.region.replace(/s*/g, ""),
detail: that.detail.replace(/s*/g, ""),
weight: that.weight
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: (res) => {
if (res.data.code === 200) {
that.$api.msg(`地址修改成功`);
}
},
});
后台
@PutMapping("update")
public Object updateLoaction(ShopAddress shopAddress){
return locationService.updateLoaction(shopAddress);
}
3.post/put/delete 传递数组
前端
let that = this;
let ids = [];
ids.push(item.id);
uni.request({
url: getApp().globalData.websiteUrl + '/location/delete',
method:'DELETE',
data:{
ids:ids
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
dataType: 'json',
success: (res) => {
if(res.data.code === 200){
that.$api.msg(`删除成功`);
}
},
});
后台
@DeleteMapping("delete")
public Object deleteLoaction(String ids){
List<String> list = Arrays.asList(ids.split(","));
return locationService.deleteLoaction(list);
}