如何将数据从POJO和控制器传递到Ajax



我通过使用@ResponseBody注释将数据作为Json从控制器传递。我的问题是 ajax 无法识别来自我的控制器的数据。当我检查 ajax 中的typeof数据时,它告诉我它是undefined

@RequestMapping(value = "/basic/Json", method = RequestMethod.POST)
    public @ResponseBody JsonResponse addCertJson(@Valid @ModelAttribute CertificateProgramme certificate, BindingResult result, Principal principal, Locale locale, MessageSource messageSource) {
        JsonResponse res = new JsonResponse();
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        certificate.setUser(user);
        if(!result.hasErrors()){
            res.setStatus("SUCCESS");
        }else{
            res.setStatus("FAIL");
            List<FieldError> allErrors = result.getFieldErrors();
            List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>();
            for (FieldError objectError : allErrors) {
                errorMesages.add(new ErrorMessage(objectError.getField(), objectError.getField() + "  " + objectError.getDefaultMessage()));
            }
            res.setErrorMessageList(errorMesages);
        }
        certificateService.save(certificate);
        return res;
    }

形式

<form method="post" th:object="${certificate}"
      th:action="@{${action1}}" modelAttribute="employee" class="form-inline inline new-item editCert">
    <input type="hidden" th:field="*{id}"/>
    <div th:replace="common/layout :: flash"></div>
    <div class="error" ></div>
    <fieldset>
        <legend th:text="${heading}"> Personal Information</legend>
        <div class="row" th:classappend="${#fields.hasErrors('fullName')}? 'error' : ''">
            <input type="text" id="fullName" class="form-control input-sm" th:field="*{fullName}"
                   placeholder="Full Name example Jane Doe"/>
            <div class="error-message" th:if="${#fields.hasErrors('fullName')}" th:errors="*{fullName}"></div>
        </div>
        <div class="row" th:classappend="${#fields.hasErrors('gender')}? 'error' : ''">
            <select th:field="*{gender}" class="form-control input-lg ">
                <option value="">[Select Gender]</option>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
            </select>
            <div class="error-message" th:if="${#fields.hasErrors('gender')}" th:errors="*{gender}"></div>
        </div>

J查询文件

 var $form = $('.editCert');
    var formData = $form.serialize();
    $form.on('submit',function(e){
        e.preventDefault();
        $.ajax(url,{
            dataType: 'json',
            data: data,
            type: "POST",
        }).done(function(response){
           if(response.status === 'SUCCESS'){
                 console.log('I am Okay' + response);
                  }else{
                  console.log('Error');
                   }
        }).fail(function(res){
            errorInfo = "";
                 for(i =0 ; i < res.errorMessageList.length ; i++){
                     errorInfo += "<br>" + (i + 1) +". " + response.errorMessageList[i].code;
                 }
                 $('.error').html("Please correct following errors: " + errorInfo);
            });
    });

错误

Uncaught TypeError: Cannot read property 'length' of undefined

我的假设是你返回的是 JsonResponse 对象,而不是 json 字符串。尝试将其解析为 json。

另外 1 个注意事项,您以错误的方式使用失败回调。它应该是

fail(function(jqXHR, textStatus, errorThrown){
   console.log(errorThrown);
})

相关内容

  • 没有找到相关文章

最新更新