2014-02-22 94 views
1

我有一个MVC弹簧控制器。我在页面加载时调用了这个ajax。ajax调用MVC弹簧控制器,未找到错误

$.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; 
    } 
} 

的了卖出期权的控制台,控制器正确。但我收到“未找到”错误。以下是开发人员工具错误:GET“MySite/custom/Service?note1 = 11”404(Not Found)。哪里不对?

回答

1

更改您的代码如下图所示:

@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); 
      }, 
+0

该路径是正确的。因为我可以看到控制台中的输出。我在项目中使用该路径进行其他ajax调用,并且它可以工作。 – Mark

+0

你正在返回结果,是否正确?它必须是一个jsp名称。 –

+0

我刚刚创建了一个类,并将所有映射放在如下所示:@RequestMapping(“/ custom”) public class CustomController @RequestMapping(value =“/ Service”,method = RequestMethod.GET) \t public String ServiceType ( \t \t \t @RequestParam( “注1”)字符串备注1, \t \t \t HttpServletRequest的请求,响应HttpServletResponse的,区域设置区域设置, \t \t \t模型模型){ \t \t字符串结果= custom.Service(备注1,请求,响应); \t System.out.println(“result:”+ result); \t返回结果; } – Mark

0

需要响应体注释添加到您的返回参数

public @ReponseBody String Service(

弹簧控制器没有返回一个视图,它可以返回的数据,与reposnsebody注解。根据您的视图解析器设置,您的原始代码将根据jsp查找结果变量。