2 回答

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
查看您的響應(yīng) JSON 是否包含該response字段。
根據(jù)日志,收到的響應(yīng)是{"Username":"a", "Password":"a"}在您正在執(zhí)行的 JS 代碼中data.response.toString(),因?yàn)轫憫?yīng)未定義。你收到Uncaught TypeError: Cannot read property 'response' of undefined錯(cuò)誤了。
我嘗試了以下代碼,它在我的系統(tǒng)上運(yùn)行:
$(document).ready(function() {
$("#LoginButtonID").click(function(){
var link = "http://localhost:9024/login/auth";
var body = "{"+
"\"Username\":\""+document.getElementById("UserNameID").value+"\", " +
"\"Password\":\""+document.getElementById("PasswordID").value+"\"" +
"}";
sendRequest(link,'POST',body);
if(data.response.toString()===("valid and successful")){
localStorage.setItem("username",document.getElementById("UserNameID").value);
alert("done!")
}else if(data.response.toString()===("failed to authenticate")){
alert("failed to login");
}
})
});
function sendRequest(link, type, body) {
var xhr = new XMLHttpRequest();
xhr.open(type, link, false);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 202 ) {
data = JSON.parse(xhr.responseText);
}else if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 401 ){
data = JSON.parse(xhr.responseText); }
}
xhr.send(body);
}
控制器代碼:
@CrossOrigin(maxAge = 3600)
@PostMapping("auth")
@ResponseBody
public ResponseEntity<?> authenticate(@RequestBody Map<String, String> body) {
// sending some response for the sake of testing
body.put ("response","valid and successful");
return new ResponseEntity<>(body, HttpStatus.ACCEPTED);
}

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
您需要使用異步請(qǐng)求。您已經(jīng)在使用 jquery,它在$.ajax()中提供了此功能,無需使用 javascript 的內(nèi)置 XMLHttpRequest。
添加回答
舉報(bào)