【问题标题】:Spring mvc check if was BindingResult in javascript responseSpring mvc检查javascript响应中是否为BindingResult
【发布时间】:2013-07-26 22:52:34
【问题描述】:

是否有明确的方法来检查 ajax 成功响应控制器是否返回带有验证错误的视图?

控制器:

if(result.hasErrors()) {
        return "place/add";
    }

javascript:

$.ajax({
        url : "<spring:url value="/place/add"/>",
        type : 'POST',
        data : $("#newPlaceForm").serialize(),
        success : function(response) {

如何检查响应是否没有验证消息?

【问题讨论】:

    标签: ajax spring spring-mvc


    【解决方案1】:

    生成一个HTTP响应码来指示错误更清晰。

    例如:response.sendError(400, "Validation failed")

    jQuery 将根据响应代码执行提供的错误处理程序。

    $.ajax( '/your/url').error(function (jqXHR) {
        if (jqXHR.status == 400) {
            console.log('Bad Request');
        }
    });
    

    这更清楚,因为在 success 处理程序中处理 错误 没有多大意义。使用浏览器开发工具也更容易调试失败的请求。

    【讨论】:

    • 但是这样我丢失了&lt;form:errors path="*"&gt;&lt;/form:errors&gt;的错误
    • 在这种情况下,只需使用response.setStatus(400)
    • 现在error: function (xhr, ajaxOptions, thrownError) { $("#newLocationBox").html(xhr); alert(xhr.status) } 有问题我无法用响应替换 div 内容
    • 已解决:$("#newLocationBox").html(xhr.responseText);,好的,我接受你的解决方案,但现在我在 firebug 中有 400 个错误请求,我处理了它,但看起来不太好
    • @donatello 这就是将状态设置为 400 的全部意义;)它在 firebug 中看起来不太好一点都不重要。关键是请求在某个时候失败了,应该这样处理。
    【解决方案2】:

    成功:函数(响应){

    if(response.status == "SUCCESS"){
    
    // success code
    
    }else{
        // show validation errors
         errorInfo = "";
         for(var i =0 ; i < response.result.length ; i++){
            errorInfo += "<br>" + (i + 1) +". " + response.result[i].code;
          }
    
         $('#errorId').html("Please correct following errors: " + errorInfo);
    
    },  error: function(e){
             alert('Error: ' + e);
         }
    

    【讨论】:

      【解决方案3】:

      我最终得到:

                      success : function(response) {
                      try {
                          var status = $.parseJSON(response);
                          if (status.status = 'OK') {
                              alertify.success("Akcja wykonana pomyślnie");
                              $("#newPlaceForm").hide();
                              $("#spotPlaces").show();
                          }
      
                      } catch (e) {
                          $("#newLocationBox").html(response);
                      }
      
                  }
      

      这对我来说似乎很清楚,我不必在 html 代码中搜索错误,如果一切正常,我只需返回只有 ${status} 字段的控制器视图并添加属性status 为字符串化jsonmodel.addAttribute("status", "{\"status\": \"OK\"}");

      【讨论】:

        猜你喜欢
        • 2018-05-19
        • 1970-01-01
        • 1970-01-01
        • 2012-12-13
        • 1970-01-01
        • 2019-07-18
        • 2020-08-27
        • 1970-01-01
        • 2015-12-24
        相关资源
        最近更新 更多