【发布时间】:2018-11-24 11:16:05
【问题描述】:
我正在尝试使用 Ajax 调用我的 Spring 控制器并提交一个表单。
函数总是检索错误窗口。我尝试将 URL 参数更改为 "/profile"、"profile" 或 "PrivateAreaController/profile",但我一直收到相同的错误.
我的main.js文件和控制器按以下顺序放置:
-->Mainfolder
-->src
-->java
-->controller
-->PrivateAreaController.java
-->resources
-->static
-->js
-->main.js
我的控制器叫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;
});
弹簧代码
@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/(yourrequestmapping参数)
【问题讨论】:
-
错误是什么?
data的内容看起来不像是有效的 JSON。
标签: java ajax spring spring-mvc spring-boot