Spring 3.1 Controller不接受ajax帖子

时间:2014-06-30 16:14:50

标签: java jquery ajax spring

我正在使用spring 3.1 MVC创建一个AJAX表单。我很困惑,已经搜索了互联网和stackoverflow解决我的问题,但到目前为止一直没有成功。我也使用Tiles 2.2.2

我收到警告:不支持请求方法'POST'

控制器方法

    @RequestMapping(value="/createProject", method=RequestMethod.POST,headers ="Accept:*/*")
         public @ResponseBody Project createProject(@RequestBody Project project){
               try {
                  projectBusiness.createProject(project);
               } catch (Exception e) {
                  e.printStackTrace();
               }
          return project;
        }
   @RequestMapping(value="/createProject", method=RequestMethod.GET)
        public ModelAndView displayCreateProjectForm(){
        ModelAndView mav = new ModelAndView("createProject");
        mav.addObject("project", new Project());
        return mav;
    }

@RequestMapping(value="/createProject", method=RequestMethod.POST,headers ="Accept:*/*") public @ResponseBody Project createProject(@RequestBody Project project){ try { projectBusiness.createProject(project); } catch (Exception e) { e.printStackTrace(); } return project; } @RequestMapping(value="/createProject", method=RequestMethod.GET) public ModelAndView displayCreateProjectForm(){ ModelAndView mav = new ModelAndView("createProject"); mav.addObject("project", new Project()); return mav; } 我的JSP

   $(function() {

    var url = $('#myForm').attr('action'); //http://localhost:7001/ProjectPortfolioTracker/app/projects/createProject
    $('#submitForm').click(function(e){
        console.log("hello");
        e.preventDefault();
        var formData = $('#myForm').serialize();
        alert(formData);

        console.log('in form click');
        $.ajax({
            type: 'POST',
            url: url,
            data:formData,
            success: function(){
               alert('success');
            },error: function(){
                alert('failure');
            },
        }).done(function() {
        alert("ajax post completed"); 
    });

    });
});

我还应该提一下我得到了通过ajax发布的实际信息,但我没有以ajax方式处理控制器代码,这意味着我仍然在方法结束时查看视图,因为更改为使用@ResponseBody和@RequestBody是问题何时开始发生

请原谅我仍在学习的可怕格式。

1 个答案:

答案 0 :(得分:0)

所以问题是@RequestMapping的Headers参数,它不喜欢Accept: / ,当我把它改为Accept时,我认为它接受任何东西:“application / json”它开始正常工作感谢所有评论试图帮助的人