Ajax表单未提交,只是刷新而已

时间:2019-03-16 19:16:28

标签: ajax spring jsp

我有一个注册新用户的表格。这是表格:

<label for="add-username" class="col-md-4 control-label">Username:</label>
  <div class="col-md-8">
    <input id="add-username" name="username" type="text" class="form-control" placeholder="username"/>
       </div>
         </div>
            <div class="form-group">
              <label for="add-password" class="col-md-4 control-label">Password:</label>
                 <div class="col-md-8">
                    <input id="add-password" name="password" type="password" class="form-control" placeholder="password"/>
                      </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-offset-4 col-md-8">
                                    <c:if test="${duplicate}">
                                        <p class="alert alert-danger">I'm sorry that username is already taken.</p>
                                    </c:if>
                                    <div id="validationRegisterUserErrors" class="alert alert-danger" style="display:none"></div>
                                    <button type="submit" id="user-register-button" class="btn btn-primary">Register</button>
                                </div>
                            </div>

在这个jsp文件的末尾,我添加了一个脚本,该脚本将表格发布在ajax中。脚本是:

  $("#user-register-button").click(function(event){
        event.preventDefault();
        registerUser();
    });
function registerUser(){
    var errorDiv = $("#validationRegisterUserErrors");

    $.ajax({
        url: 'user',
        type: 'POST',
        headers:{
            'Content-type': 'application/json'
        },
        'dataType' : 'json',
        data: JSON.stringify({
            firstName: $('#add-first-name').val(),
            lastName: $('#add-last-name').val(),
            email: $('#add-email').val(),
            username: $('#add-username').val(),
            password: $('#add-password').val()
        })
    }).success(function(data){
        errorDiv.empty();
        errorDiv.hide();
        window.location="login";
    }).error(function (data, status){
            errorDiv.empty();
            errorDiv.show();
            $.each(data.responseJSON.fieldErrors, function (index, validationError){
                errorDiv.append(validationError.message);
                errorDiv.append("<br>");
            });
    });
}

URL“用户”位于usercontroller中:

@ResponseBody
    @ResponseStatus(HttpStatus.CREATED)
    @RequestMapping(value="/user", method=RequestMethod.POST)
    public User registerUser(@Valid @RequestBody User user, Model model){
        user.setPassword(encoder.encode(user.getPassword()));
        user.setRole("ROLE_USER");
        try {
            userDao.createUser(user);
        } catch (DuplicateKeyException e){
            boolean duplicate = true;
            model.addAttribute("duplicate", duplicate);
        }
        return user;
    }

但是当我单击注册时,页面会刷新,并在URL中写入http://localhost:8080/signup?firstName=abc&lastName=adcd&email=adc%40ll.com&username=abcdef&password=9376868355 但是没有添加用户。即使我没有填写表格并单击注册按钮,也不会出现验证错误,它只会刷新页面。可能是什么问题?

1 个答案:

答案 0 :(得分:0)

感谢您的大力参与!

问题出在headers:{...}中。我将我的ajax更改为以下内容,问题得以解决:

function registerUser(){
    var errorDiv = $("#validationRegisterUserErrors");
    $.ajax({
        url: 'user',
        type: 'POST',
        data: JSON.stringify({
            firstName: $('#add-first-name').val(),
            lastName: $('#add-last-name').val(),
            email: $('#add-email').val(),
            username: $('#add-username').val(),
            password: $('#add-password').val(),
            homeAddress:$('#add-home-add').val(),
            workAddress:$('#add-work-add').val(),
            phoneNumber:$('#add-phone').val(),
            jobPosition:$('#add-job').val(),
            fieldOfStudy:$('#add-field').val()
        }),
        headers:{
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        'dataType' : 'json'
    }).success(function(data, status){
        alert("User has been added.");
        $('#add-first-name').val('');
            $('#add-last-name').val('');
             $('#add-email').val('');
             $('#add-username').val('');
             $('#add-password').val('');
        $('#add-home-add').val('');
        $('#add-work-add').val('');
        $('#add-job').val('');
        $('#add-field').val('');
        $('#add-phone').val('');
        errorDiv.hide();
        window.location="login";
    }).error(function (data, status){
        errorDiv.empty();
        errorDiv.show();
        $.each(data.responseJSON.fieldErrors, function (index, validationError){
            errorDiv.append(validationError.message);
            errorDiv.append("<br>");
        });
    });
}