我正在尝试使用 Ajax 调用我的 Spring Controller 并提交表单。
函数总是检索错误窗口。我尝试将 URL 参数更改为 "/profile"、"profile" 或 "PrivateAreaController/profile",但我不断收到相同的错误.
我的 main.js
文件和 Controller 按以下顺序放置:
-->Mainfolder
-->src
-->java
-->controller
-->PrivateAreaController.java
-->resources
-->static
-->js
-->main.js
我的 Controller 名为PrivateAreaController
Ajax 代码
$('#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;
});
Spring代码
@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/(your请求映射参数)
最佳答案
我找到了答案..我需要添加
@CrossOrigin(origins = "http://localhost:8080 ")
在@RequesMapping参数之前,将ajax调用的url参数修改为url: ' http://localhost:8080/(your请求映射参数)
关于java - Ajax 请求未调用 Spring boot Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50861521/