【问题标题】:MVC Spring controller - ajax Not working properlyMVC Spring 控制器 - ajax 无法正常工作
【发布时间】:2014-03-12 04:13:39
【问题描述】:

我有一个 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";

alert(result) 成功时,它会打印页面的整个代码。

【问题讨论】:

  • 你能显示你的上下文配置吗?由于您使用的是 ResponseBody,因此只应输出结果字符串。
  • 如果我删除 @responseBody 它仍然有同样的问题。
  • 结果是字符串。
  • 另外,如果我删除 @responseBody 并在控制器中返回一个字符串。出现同样的问题!
  • “结果”等于什么?确切的字符串将被发送到客户端。

标签: ajax spring-mvc


【解决方案1】:

你的AJAX url和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;
}

【讨论】:

    猜你喜欢
    • 2020-01-22
    • 2012-09-03
    • 2013-08-02
    • 2013-02-03
    • 2013-07-26
    • 1970-01-01
    • 2014-07-23
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多