MVC Spring控制器 - ajax无法正常工作

时间:2014-03-12 04:13:39

标签: ajax spring-mvc

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

$.ajax({
        type:       "get",
        url:        'custom/topic',
        data:       "email1=" + email1 + "&email2=" + email2 ,

        async:   false,
        success:    function(result) {
                    alert(result);
        },
        error: function (xhr, desc, error) {
            window.alert('description' + desc);
            window.alert('error' + error);
        }
    });

我的控制器是:

@RequestMapping(value="/topic", method=RequestMethod.GET)
    public String topic(
            @RequestParam("x1") String x1,
            @RequestParam("x2") String x2) {

    System.out.println("test");
    String result1 = custom.topic(x1, x2);

    return "test";

警报(结果)成功后,它会打印整个页面代码。

1 个答案:

答案 0 :(得分:0)

您的AJAX网址和topic方法签名无效,

喜欢:

如果您有@RequestMapping(value="/topic", method=RequestMethod.GET),并且您的班级映射@RequestMapping(value="/customprop")也不要忘记添加...

然后在表单操作标记中定义GET url,如:

 <c:url value="/customprop/topic" var="getUrl"/>
  <form action="${getUrl}" id="tellfriendform" method="GET">

并在您的AJAX调用中检索网址,如:

$('#tellfriendform').submit(function(e){
            var postData = $(this).serializeArray();
            var formURL = $(this).attr("action");
            $.ajax(
              {
                type: "GET",
                url: formURL,
                data: postData,
                dataType: "json",
                success: function(data) {
                alert(JSON.stringify(data));
                },
                error:function(e){
                    alert('error: '+e);
                }
              });
            e.preventDefault(); // STOP default action
            e.unbind(); //unbind. to stop multiple form submit.
        });

您应该更改主题方法签名,如:

使用Spring 3.0.4时: 那么,你GET应该是这样的:

    @RequestMapping(value="/topic", method=RequestMethod.GET)
    public @ResponseBody String topic(HttpServletRequest request,
                                      HttpServletResponse response){
     System.out.println("test");
     String email = request.getParameter("email");
     String email2 = request.getParameter("email2");
     String result1 = custom.topic(email, email2);

     return email+ ", "+email2;
}