最近在做一个前后端不分离的项目,所以前后端的代码都是同一个人写,前端是用的ajax请求后台。由于有两年时间没有写前端代码了,所以又去重新学习了下ajax的应用。
第一种方式是表单:
1.ajax
$.ajax({
// 请求url
url: "/contextPath/xxx/xxxx",
// 请求方式
type: "post",
// 预期服务器返回的数据类型
dataType: "json",
// 发送到服务器的数据
data: {
"variableName1": variableValue1,
"variableName2": variableValue2
},
// 请求成功后的回调函数
success: function (result) {
// 浏览器控制台打印结果
console.log(result);
// 这里可以写请求成功之后的业务逻辑
},
// 请求失败后的回调函数
error: function (e) {
console.log(e.status);
console.log(e.responseText);
}
});
2.controller
package com.xx.xxx.xxxx.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("xxx")
public class BillBatchInfoController {
@RequestMapping("xxxx")
@ResponseBody
public Integer xxxx(@RequestParam String variableName1, @RequestParam String variableName2) {
return 1;
}
}
第二种方式是json
2.1 ajax
$.ajax({
// 请求url
url: "/contextPath/xxx/xxxx",
// 请求方式
type: "post",
// 预期服务器返回的数据类型
dataType: "json",
// 发送到服务器的数据
data: JSON.stringify({
"variableName1": variableValue1,
"variableName2": variableValue2
}),
// 发送信息至服务器时内容编码类型,默认值: "application/x-www-form-urlencoded"。
contentType: "application/json; charset=UTF-8",
// 请求成功后的回调函数
success: function (result) {
// 浏览器控制台打印结果
console.log(result);
// 这里可以写请求成功之后的业务逻辑
},
// 请求失败后的回调函数
error: function (e) {
console.log(e.status);
console.log(e.responseText);
}
});
2.controller
package com.xx.xxx.xxxx.controller;
import com.xx.xxx.xxxx.dto.RequestParams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("xxx")
public class BillBatchInfoController {
@RequestMapping("xxxx")
@ResponseBody
public Map<String, Object> listReceiveBills(@RequestBody RequestParams requestParams) {
return new HashMap<>();
}
}
3.参数类
package com.xx.xxx.xxxx.dto;
public class RequestParams {
private String variableName1;
private String variableName2;
public String getVariableName1() {
return variableName1;
}
public void setVariableName1(String variableName1) {
this.variableName1 = variableName1;
}
public String getVariableName2() {
return variableName2;
}
public void setVariableName2(String variableName2) {
this.variableName2 = variableName2;
}
}
留在最后:此博客仅为本人笔记,如若参考,请谨慎使用。