将Spring3 MVC错误移至Ajax?

时间:2012-05-24 16:34:55

标签: java ajax spring spring-mvc

我正在开发一个项目,为Spring-MVC项目添加一些Ajax。我删除了标签

<form:errors path="fieldName"/>

那会插入JSP的错误,现在我正在尝试制作一些Ajax代码来显示页面上的错误。任何人都应该如何更新以下代码以显示错误消息而不是错误?

success: function(response)
          {
          // we have the response 
            $('#error').hide('fast');   
            if(response.status == "SUCCESS")
            {
                $('#error').hide('fast');  
                alert("Thanks for submitting.  We will get back to you as soon as possible.\n\n" + response.result);
                $('#error').hide('slow');

            }else
            {
              errorInfo = "";
              for( i = 0 ; i < response.result.length ; i++){
                  errorInfo += "<br>" + (i + 1) +". " + response.result[i].code;
              }
              $('#error').html("Please correct following errors: " + errorInfo);
              $('#info').hide('slow');
              $('#error').show('slow');
              $('#input').show('slow');
          }       
        },  
        error: function(e){  
          alert('Error: ' + e);  
        }  
      });  

以上代码用于显示错误,但不显示错误消息

下面是我的java代码:

    @RequestMapping(value = "/ajax.html", method = RequestMethod.POST)
    public @ResponseBody
    JsonResponse addMessage(@Valid
            @ModelAttribute(value = "memberrequest") MemberRequest memberrequest,
            BindingResult result) {

            JsonResponse res = new JsonResponse();


        if (!result.hasErrors()) {
            res.setStatus("SUCCESS");

            // Setting data over to RT

            String Ticket = zzz.sentWebRequest(memberrequest);

            /*
             * Setting out the ticket number to be displayed to user
             */

            Map<String, Object> model = new HashMap<String, Object>();
            Ticket t = new Ticket();
            t.setTicketDetails(Ticket);

            model.put("ticket", t);

            res.setResult(Ticket);
        } else {
            res.setStatus("FAIL");
            res.setResult(result.getAllErrors());
        }

        return res;
    }
}

JSON类:

  

public class JsonResponse {private String status = null;私人的   对象结果= null;

     

public String getStatus(){return status; }

     

public void setStatus(String status){this.status = status; }

     

public Object getResult(){return result; }

     

public void setResult(Object result){this.result = result; }

     

}

2 个答案:

答案 0 :(得分:1)

尝试使用response.result[i].defaultMessage代替response.result[i].code

答案 1 :(得分:0)

response.result

W3C根据XMLHttpRequest 2 result对象中没有response属性

如果在响应表单服务器端传递一些文本值。你可以将response.responseText作为一个整体文本。