如何使用JQuery和Spring Controller提交表单

时间:2017-03-24 07:19:03

标签: javascript jquery ajax spring spring-boot

当我禁用ajax功能时,我很难理解为什么我的表单提交成功。当我在输入表单上启用ajax时。我提交的输入值未提交。我使用chrome开发人员工具来检查提交的FormData。我意识到什么都没有提交。 因此,我收到错误,要求我填写这些字段。

控制器

    @PostMapping(value = "/basicAjax.json")
    @ResponseBody
    public ResponseEntity<Object> addCertJson(@Valid @ModelAttribute CertificateProgramme certificate, BindingResult result, Principal principal) {
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        certificate.setUser(user);
        if (result.hasErrors()) {
            List<String> errors = result.getAllErrors().stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.toList());
            return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
        } else {
            certificateService.save(certificate);
            return new ResponseEntity<>(HttpStatus.ACCEPTED);
        }
    }

JS脚本

var $form = $('.editCert');
var formData = $form.serialize();
var url = $form.attr('action');
var storage = {};
$.each($('.editCert').serializeArray(), function(i, field) {
    storage[field.name] = field.value;
});

$form.on('submit',function(e){
    e.preventDefault();
    $.ajax(url,{
            dataType: 'JSON',
            data: storage,
            type: "POST",
        }).done(function(response){
           if(response.status === 'SUCCESS'){
                 console.log('I am Okay' + response);
                  }else{
                  console.log('Holly Molly');
                   }
        }).fail(function(jqXHR, textStatus, errorThrown){
          var errorInfo="";
          for(i =0 ; i <jqXHR.responseJSON.length ; i++){
                           errorInfo += "<br>" + (i + 1) +". " + jqXHR.responseJSON[i];
                       }
                    var $myerror =  $form.find('.flash').addClass(' failure');
                        $myerror.html("Please correct following errors: " + errorInfo);
           });
    });

表格

<form  method="post" th:object="${certificate}"
      th:action="@{${action1}}" class="form-inline inline new-item editCert">
    <input type="hidden" th:field="*{id}"/>
    <div th:replace="common/layout :: flash"></div>
    <div class="flash"></div>
    <fieldset>
        <legend th:text="${heading}"> Personal Information</legend>
        <div class="row" th:classappend="${#fields.hasErrors('fullName')}? 'error' : ''">
            <input type="text" 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>
        <div class="row" th:classappend="${#fields.hasErrors('date')}? 'error' : ''">
            <input th:type="date" data-value="20/04/2015" class="form-control input-sm datepicker" th:field="*{date}"
                   placeholder="Date Of Birth"/>
            <div class="error-message" th:if="${#fields.hasErrors('date')}" th:errors="*{date}"></div>
        </div>

1 个答案:

答案 0 :(得分:0)

解决了我的问题,将表单迭代移动到了提交$ .ajax提交函数

$form.on('submit',function(e){
    e.preventDefault();
    $.each($(this).serializeArray(), function(i, field) {
        storage[field.name] = field.value;
    });
   console.log(storage);
    $.ajax(url,{
            //dataType: 'json',
            data: storage,
            type: "POST",
        }).done(function(response){
                 console.log('I am Okay' + response);
        }).fail(function(jqXHR, textStatus, errorThrown){
        console.log(jqXHR);
          if(jqXHR.status === 400){
          var errorInfo="";
          for(i =0 ; i <jqXHR.responseJSON.length ; i++){
                           errorInfo += "<br>" + (i + 1) +". " + jqXHR.responseJSON[i];
                       }
                    var $myerror =  $form.find('.flash').addClass(' failure');
                        $myerror.html("Please correct following errors: " + errorInfo);
            }
           });
    });