这些代码是我的Spring Boot项目的RestController,@RestController@RequestMapping(value="/rest/user")public class UserRestController { @Autowired private UserService userService; @PostMapping("login") public ResponseEntity<Boolean> authenticated(@RequestBody User user) { System.out.println(user.getUsername() +":"+ user.getPassword()); //This line returns NULL password value Boolean blogin = userService.authenticate(user.getUsername(), user.getPassword()); if(!blogin) return new ResponseEntity<Boolean>(blogin, HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<Boolean>(blogin, HttpStatus.OK); }}下面的代码是JQuery ajax Java脚本代码。function ajax_login_submit() { var user = { username: $("#username").val(), password: $("#password").val() }; console.log(user); $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "rest/user/login", data: JSON.stringify(user), dataType: 'json', success: function (data) { var resultJson = JSON.stringify(data); $('#helloUserDiv').html(resultJson); console.log("SUCCESS : ", data); alert(data); }, error: function (e) { var resultJson = e.responseText; $('#helloUserDiv').html(resultJson); console.log("ERROR : ", e); } });}console.log(user); 的Java脚本返回正确的值。{"username":"joseph","password":"password"}但是在RestController代码中,密码值缺少“ NULL”。该行System.out.println(user.getUsername() + ":" + user.getPassword());返回奇怪的值,"joseph:null" 是否有可能JQuery ajax方法不将json值传输到REST服务器?如果我犯了一些错误,请告诉我如何将json值正确发送到REST服务器。
1 回答
DIEA
TA贡献1820条经验 获得超2个赞
试试这个:
$.ajax({
type: "POST",
contentType: "application/json",
url: "rest/user/login",
data: JSON.stringify({"username": $("#username").val(), "password": $("#password").val()}),
dataType: 'json',
success: function (data) {
var resultJson = JSON.stringify(data);
$('#helloUserDiv').html(resultJson);
console.log("SUCCESS : ", data);
alert(data);
},
error: function (e) {
var resultJson = e.responseText;
$('#helloUserDiv').html(resultJson);
console.log("ERROR : ", e);
}
});
添加回答
举报
0/150
提交
取消