[英]Sending object in ajax get-method Javascript
I am trying to recieve an User-object from the database using this rest-method: 我正在尝试使用此其余方法从数据库中接收用户对象:
@RestController
@RequestMapping("/rest/users")
public class UserRestController {
@Autowired
private UserService service;
@RequestMapping(method = RequestMethod.GET)
public Collection<User> getAllUsers(@RequestBody(required = false) User user) throws BadHttpRequest {
System.out.println(user);//ALWAYS RETURNING NULL :(
if (user == null) {
return service.getAllUsers(); //Always returns this!
} else if (user.getUserId() == null) {
return Collections.singletonList(service.getUserByEmail(user.getUsername()));//I want this
} else if(user.getUsername() == null){
return Collections.singletonList(service.getUserById(user.getUserId()));
}else{
throw new BadHttpRequest(new Exception("User id/email mismatch"));
}
}
I use this javascript: 我使用这个javascript:
var user = [{ "username": "fms7@hotmail.no", "userId": 1}];
$.ajax({
type: "get",
url: "/rest/users/",
data: JSON.stringify({ User: user }),
success: function(data){alert(data);},
error: function(errMsg) {
alert("bais");
}
});
Does anyone have an idea of what I do wrong? 有人知道我做错了什么吗?
I think this is creating problem. 我认为这正在造成问题。
data: JSON.stringify({ User: user })
You should change it to: 您应该将其更改为:
data: { User:JSON.stringify(user) }
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.