java - Ajax 请求未调用 Spring Boot 控制器
问题描述
我正在尝试使用 Ajax 调用我的 Spring 控制器并提交表单。
函数总是检索错误窗口。我尝试将 URL 参数更改为"/profile"、"profile"或"PrivateAreaController/profile",但我一直收到同样的错误。
我的main.js
文件和控制器按以下顺序放置:
-->Mainfolder
-->src
-->java
-->controller
-->PrivateAreaController.java
-->resources
-->static
-->js
-->main.js
我的控制器被称为PrivateAreaController
阿贾克斯代码
$('#sampleForm').submit(
function(event) {
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var data = 'firstname='
+ encodeURIComponent(firstname)
+ '&lastname='
+ encodeURIComponent(lastname);
$.ajax({
type : "POST",
dataType: "json",
url : '@Url.Action("callingcontroller","PrivateAreaController")',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
return false;
});
弹簧代码
@RequestMapping(value = "/profile", method = RequestMethod.POST)
public @ResponseBody
String processAJAXRequest(
@RequestParam("firstname") String firstname,
@RequestParam("lastname") String lastname ) {
String response = "";
System.out.println("working");
return response;
}
HTML 表单
<form id="sampleForm" method="post" action="/profile">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<button type="submit" name="submit">Submit</button>
</form>
编辑:
我找到了答案..我需要添加
@CrossOrigin(origins = "http://localhost:8080")
在@RequesMapping
参数之前并将ajax调用的url参数更改为url:' http://localhost:8080/(你的requestmapping参数)
解决方案
我找到了答案..我需要添加
@CrossOrigin(origins = " http://localhost:8080 ")
在 @RequesMapping 参数之前并将 ajax 调用的 url 参数更改为 url:' http://localhost:8080/(你的requestmapping 参数)
推荐阅读
- ios - 如何在与默认目标中的数据不同的数据/应用程序(SQLite db,UserDefaults)上运行 Xcode 测试?
- r - R:子集基因模型
- php - 如何在循环中添加具有相同月份的数组?
- angular - nginx 总是显示默认的欢迎页面
- r - 如何使用 Rstudio(Windows)从 hotmail 到 hotmail 发送电子邮件?
- pandas - Panads:试图操纵数据
- linux - “systemctl suspend”命令所需的根权限
- charts - 在 Chart.js 中将单个分组条拆分为多个条
- python - 使用 .isin() 过滤数据仅适用于 1 列
- python - 泛型类型提示 python