小编典典

如何使用ajax请求从Spring控制器返回视图?

ajax

我使用jquery发出ajax请求,这将调用以下spring控制器:

@RequestMapping(value = "/dialogController", method = RequestMethod.POST)
public String dialogController(Model model, @RequestBody MyClass myclass) {
  myClass.setTitle("SUCCESS");       
  model.addAttribute("myClass",myClass);
  return "dialogContent";  //this resolves to dialogContent.jsp
}

但是我收到以下错误:

org.springframework.web.HttpRequestMethodNotSupportedException: 
Request method 'POST' not supported

如果需要,这里是我使用jQuery进行的ajax调用:

   jq.postJSON("/dialogController", myClass, function(data) {
      myDialog.html(data);
      myDialog.dialog('open'); 
      //dialog settings previously assigned, 
      //but the success callback function is not reached anyway
    });

编辑 如果使用以下命令,则会出现相同的错误:

jq.ajax({
  type: 'POST',
  url: "/dialogController",
  data:myClass,
  success:  function(data) {            
         previewDialog.html(data);
         previewDialog.dialog('open');
  });

阅读 225

收藏
2020-07-26

共1个答案

小编典典

对于在家的观众…我发现问题是由于控制器中定义的方法签名与ajax调用不匹配。我Model model从控制器方法中删除了参数。然后,我还意识到我还必须返回新的模型和视图。这是工作代码:

var myJSON  = {"title":"help"}; 
myJSON = JSON.stringify(myJSON);

<c:url var="postAndView" value="/PostJSONMAV" />
...
jQuery.ajax({
    type: 'POST',
    url: "${postAndView}",
    data:myJSON,
    contentType: "application/json",
    success:  function(data) {          
        previewDialog.html(data);
        previewDialog.dialog('open');
    }
});

我更改为ajax调用,但jQuery.postJSON()也可能会正常工作。下面显示的是新的控制器代码,该代码正确地将新对象添加到模型中并返回jsp页面,该页面在对话框中打开:

@RequestMapping(value = "/PostJSONMAV", method = RequestMethod.POST)
public  ModelAndView postJSON(@RequestBody MyClass myClass) {
    ModelAndView mav = new ModelAndView();
    myClass.setTitle("SUCCESS");
    mav.setViewName("dialogContent");
    mav.addObject("myClass", myClass);
    return mav;     
}
2020-07-26