通过ajax将数据传递给spring mvc控制器

时间:2013-10-27 12:49:11

标签: java jquery ajax spring

我如何通过ajax将数据正常传递给MVc控制器操作 现在在我的js文件中

$.ajax({
    type: "POST",
    url:url,
    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){
        if(combo.getActualValue() != null){
            getUserEvents(id);
        }
        else{
            $.ajax({
                url:"/WebElanceSh/events",
                success:function(result){
                    json = result;
                    scheduler.parse(json, "json");
                }
            });
        }
    }
});

并在我的控制器中

@RequestMapping(value = "events/add/", method = RequestMethod.POST)
public void addEvent(@RequestBody  String start_date,
                     @RequestBody  String end_date,
                     @RequestBody  String text,
                     @RequestBody  Integer userId){
    Event event = new Event(text,start_date,end_date);

    if(userId == -1){
         TestData.getInstance().AddEvent(-1, event);

    }
    else {
        TestData.getInstance().AddEvent(userId, event);

    }

}

但我一直都有 无法加载资源:服务器响应状态为415(不支持的媒体类型)

1 个答案:

答案 0 :(得分:1)

为与ajax请求匹配的Object建模,然后将其用作请求参数:#

public class MyCommandObject {
   private Date start_date;
   private Date end_date;
   private String text;
   private Integer userId;

   /** Constructor wihtout parameter needed. */
   public MyCommandObject() {}

   Getter and Setter
}


@RequestMapping(value = "events/add/", method = RequestMethod.POST)
public void addEvent(@RequestBody  MyCommandObject command){ ... }