我遇到了一个奇怪的问题,我想在AJAX中使用以下代码执行POST请求:
$('.login-form').on('submit', function(e) {
e.preventDefault(); // to block the behavior from HTML form
$.ajax({
type: "post",
url: "http://localhost:8080/login",
data: JSON.stringify({
username:"lmezkml",
password:"ezaezaeza"
}),
success: function(data, textStatus, jqXHR) {
console.log('success');
},
contentType: "application/json; charset=utf-8",
dataType: 'json'
});
});
即使在关注此问题的多个主题之后,我仍然遇到麻烦。 例如,我尝试过:
dataType: 'json'
contentType : "application/json; charset=utf-8"
XMLHttpRequest()
$.post
Chrome的检查员给我:
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/login
Request Method:POST
Status Code:400 Bad Request
**Request Headersview source**
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Connection:keep-alive
Content-Length:45
Content-Type:application/json; charset=UTF-8
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/login
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
**Request Payloadview source**
{username:lmezkml, password:ezaezaeza}
password: "ezaezaeza"
username: "lmezkml"
**Response Headersview source**
Connection:close
Content-Type:application/json;charset=UTF-8
Date:Wed, 09 Dec 2015 14:39:11 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
这是我的服务器代码:
@RequestMapping(value="/login", method=RequestMethod.POST, produces={"application/json"}, consumes={"application/json"})
public ResponseEntity<?> hello(@RequestParam("name") String username, @RequestParam("password") String password) {
System.out.println("username : " + username + " password : " + password);
try {
LdapContext ctx = ActiveDirectory.getConnection(username, password);
ctx.close();
}
catch(Exception e) {
//Failed to authenticate user!
e.printStackTrace();
return new ResponseEntity<>(null, HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(null, HttpStatus.OK);
}
希望它有助于解决我的400个错误请求的问题。
提前致谢。
答案 0 :(得分:0)
我认为,服务器上的问题。
尝试发送到服务器js对象,而不是字符串,或在服务器中调试。
答案 1 :(得分:0)
感谢Alex Repeckiy,我解决了我的问题。真正的问题是数据存储在Body中,而ive试图通过参数获取它们。
如果它可以帮助Spring Framework用户,我使用@RequestBody
而不是@RequestParam
来更改我的功能。
谢谢!