目前实现的有两种传参方式。请先理解,勿单纯复制粘贴。
方式一:
前端js:
function update(){
var d = {};
d.userId = 30;
d.username = "Sunpeng.Guo";
$.ajax({
url: "update",
data: JSON.stringify(d),
//type、contentType必填,指明传参方式
type: "POST",
contentType: "application/json;charset=utf-8",
success: function(response){
//前端调用成功后,可以处理后端传回的json格式数据。
if(response.success){
alert(response.message);
}
}
});
}
后端Controller
@Controller
public class SwitchProduct{
@RequestMapping(value="/update")
@ResponseBody---加上该注解表明该方法返回值均自动转为json格式传给前端
public Object update(@RequestBody JSONObject params){
//@RequestBody只能给方法的参数注解,表明一次接收到请求参数
//JSONObject为alibaba的fastjson包下类,推荐使用。另外也可以使用String来接收前端的json格式传参。
Integer id = params.getInteger("userId");
String name = params.getString("username");
//以上就是获取到参数体内id和name。后面再加上自己的业务逻辑即可。如果是dubbo方式的consumer,请将service注入进来,直接调用即可
Map<String,Object> map = new HashMap<>();
map.put("success",true);
map.put("message","更新成功了!");
return map;
}
}
方式二:
前端js:
function update(){
$.post(
"update",
{"userId":30,"username":"sunpeng.guo"},
function(response){
if(response.success){
alert(response.message);
}
},
"json"
)
}
后端Controller
@Controller
public class SwitchProduct{
@RequestMapping(value="/update")
@ResponseBody
public Object update(HttpServletRequest request){
//HttpServletRequest 为javax.servlet.http包下
String name = request.getParameter("username");
int id = Integer.parseInt(request.getParameter("userId"));
//todo 加自己的处理逻辑
Map<String,Object> map = new HashMap<>();
map.put("success",true);
map.put("message","更新成功了!");
return map;
}
}
两种js脚本编写方式,对应不同的后端传参方式。以后有新发现的传参方式也会更新到该文章下。