当@PathVariable在spring mvc中使用时,ajax不起作用

时间:2014-11-28 08:04:31

标签: jquery ajax jsp spring-mvc

我需要在一个页面中添加ajax函数。但它在春季mvc中不能与@PathVariable一起使用 page1.jsp

<li><a href="page2/sss">WatchEvent</a></li>

1)它正常工作 在控制器

@RequestMapping(value = "page2/{id}", method = RequestMethod.GET)
public ModelAndView WatchEvent(@PathVariable("id")String id) {
System.out.println("In getplayback :"+id);   
 List<modelone> getdetails=Serviceone.detailsToUser(id);    
System.out.println("In getplayback from db:"+getdetails);    

return new ModelAndView("page2","getdetails",getdetails);    
}    

此处详细信息发送至第2页 2))但是,不是wordk    Page2.jsp

<script type="text/javascript">
 $(document).ready(function() {
    alert("ready");
    var fun="event";

    var savedata = {    
            action:fun,             
            };
     $.ajax({
         url : "events",
         type : "POST",
         datatype:"json",
         data: savedata,
            error:function(){
                alert("Error");
            },
            success: function() { 
                alert("success");   

            }    
         });
});
</script> `

但是不要去下面的控制器。

@RequestMapping(value="events",method=RequestMethod.POST)
 public @ResponseBody  String GetSomeEvents(){    
System.out.println("In someevent********************");    
String todayDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.print("today"+todayDate);
List<modelone> getlist=Serviceone.getSomeEvents();   

    return "success";   
 }

结果是警告错误。

在萤火虫中 POST ....... / page2 / events

405方法不允许

2 个答案:

答案 0 :(得分:4)

按如下方式修改您的操作后尝试:

@RequestMapping(value = "events", method = RequestMethod.POST)
public @ResponseBody String GetSomeEvents(@RequestParam String action) {    
    System.out.println("In someevent********************");    
    String todayDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
    System.out.print("today" + todayDate);
    List<modelone> getlist = Serviceone.getSomeEvents();   

    return "success";   
}

修改是将您的请求参数添加到您的操作参数。

答案 1 :(得分:0)

在ajax调用之前放这个:

$.ajaxSetup({ 
    scriptCharset: "utf-8", 
    contentType: "application/x-www-form-urlencoded; charset=UTF-8"
});