ajax 调用 MVC Spring 控制器,未找到错误



我有一个MVC Spring控制器。我在页面加载时称之为 ajax。

$.ajax({
            type:       "get",
            url:        'custom/Service',
            data:       "note1=" + "11",
            dataType:   "json",
            async:   false,
            success:    function() {
                        alert("1");
            },
            error:function (xhr, ajaxOptions, thrownError){
                if(xhr.status == 200 && xhr.statusText == 'parsererror'){
                    window.location.reload();
                } else {
                    alert(xhr.status+","+xhr.statusText);
                    alert(thrownError);
                }
            }    
        });

我的控制器是:

@RequestMapping("/custom")
public class CustomController {
    @RequestMapping(value="/Service", method=RequestMethod.GET)
        public String Service(
                @RequestParam("note1") String note1,
                HttpServletRequest request, HttpServletResponse response, Locale locale,
                Model model) {
            String result = custom.Service(note1, request, response);
        System.out.println("result: " + result);
        return result;
    }
}

控制器的输出在控制台中是正确的。但是我收到"未找到"错误。这是开发人员工具错误:获取"我的网站/自定义/服务?note1=11"404(未找到)。怎么了?

像下面这样更改代码:

@RequestMapping(value="/Service", method=RequestMethod.GET)
        public @ResponseBody String Service(
                @RequestParam("note1") String note1,
                HttpServletRequest request, HttpServletResponse response, Locale locale,
                Model model) {
            String result = custom.Service(note1, request, response);
        return result;
    }

您可以在 ajax 成功函数中访问结果。

success:    function(result) {
                        alert(result);
            },
您需要

将响应正文注释添加到返回参数中

 public @ReponseBody String Service(

弹簧控制器不必返回视图,它可以返回带有 reposnsebody 注释的数据。原始代码将根据视图解析程序设置将结果变量作为 jsp 查找。

最新更新