使用 Spring 和 Maven,我构建了一个 WAR 项目并将其部署到本地 Tomcat 服务器,当我使用浏览器访问 API 时,它可以正常工作:
http://localhost:8015/keystroke-backend/user
我得到了:
[{"id":1,"username":"bilal","password":"pass"}]
但是当我使用 AJAX 使用 JQuery 访问它时,没有任何反应:
$(document).ready(function() {
// Event to check the input data
$("#login-form").submit(function(e) {
e.preventDefault();
$.ajax({
url: "http://localhost:8015/keystroke-backend/user"
}).then(function(data) {
alert("success");
});
});
});
没有任何反应。
这是 GET API:
@Controller
@RequestMapping("/user")
public class KeystrokeController {
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<User>> doGetUsers() {
List<User> usersList = new ArrayList<User>();
try {
// Get the list of users from the database
usersList = UsersDB.getDB().getUsers();
return new ResponseEntity<List<User>>(usersList, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<List<User>>(usersList, HttpStatus.NOT_ACCEPTABLE);
}
}
}
我从控制台看到这个错误:
XMLHttpRequest cannot load http://localhost:8080/testing-client/test/server-status/1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
请注意,当我使用相同的代码访问其他内容时,如下所示:
url: "http://rest-service.guides.spring.io/greeting"
它有效。有什么想法吗?
最佳答案
将您的输入类型更改为按钮不提交,并在此更改。永远不要使用按钮类型提交给 ajax。
$("#login-form").click(function(e) {
关于javascript - 无法请求使用 JQuery 将 GET API 部署到本地 Tomcat 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37223961/