我尝试在Spring MVC中向我的控制器发出一个AJAX查询。
我的操作代码是:
@RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(@RequestParam(value = "start_date") String start_date, @RequestParam(value = "end_date") String end_date, @RequestParam(value = "text") String text, @RequestParam(value = "userId") String userId){
//some code
}
我的Ajax查询是:
$.ajax({
type: "POST",
url:url,
contentType: "application/json",
data: {
start_date: scheduler.getEvent(id).start_date,
end_date: scheduler.getEvent(id).end_date,
text: scheduler.getEvent(id).text,
userId: userId
},
success:function(result){
//here some code
}
});
但我收到了一个错误:
必需的字符串参数''start_date不存在
为什么呢?
据我所知,我将其呈现为(@RequestParam(value = "start_date") String start_date
UDP
现在我给404
我班上的数据
public class EventData {
public String end_date;
public String start_date;
public String text;
public String userId;
//Getters and setters
}
我的js AJAX调用是:
$.ajax({
type: "POST",
url:url,
contentType: "application/json",
// data: eventData,
processData: false,
data: JSON.stringify({
"start_date": scheduler.getEventStartDate(id),
"end_date": scheduler.getEventEndDate(id),
"text": scheduler.getEventText(id),
"userId": "1"
}),
控制器动作:
@RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(@RequestBody EventData eventData){
}
JSON数据是:
end_date: "2013-10-03T20:05:00.000Z"
start_date: "2013-10-03T20:00:00.000Z"
text: "gfsgsdgs"
userId: "1"
答案 0 :(得分:37)
在服务器端,您希望您的请求参数作为查询字符串,但在客户端,您发送一个json对象。要绑定json,您需要创建一个包含所有参数的类,并使用@RequestBody注释而不是@RequestParam。
@RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(@RequestBody CommandBean commandBean){
//some code
}
Here is更详细的解释。
答案 1 :(得分:0)
我有同样的问题..我通过在post请求中指定config params来解决它:
var config = {
transformRequest : angular.identity,
headers: { "Content-Type": undefined }
}
$http.post('/getAllData', inputData, *config*).success(function(data,status) {
$scope.loader.loading = false;
})
config 是我包含的参数,它开始工作.. 希望它有所帮助:)
答案 2 :(得分:0)
Spring引导代码
@RequestMapping(value = "events/add", method = RequestMethod.POST)
public void addEvent(@RequestParam(value = "start_date") String start_date, @RequestParam(value = "end_date") String end_date, @RequestParam(value = "text") String text, @RequestParam(value = "userId") String userId){
//some code
}
要发送的邮递员请求链接:使用邮递员中的Parmas添加参数和值,并查看以下请求链接。
http://localhost:8080/events/add?start_date=*someValue*&end_date=*someValue*&text=*someValue*&userId=*someValue*