当我尝试保存数据时,Ajax无法正常工作

时间:2017-03-18 11:43:20

标签: java jquery ajax spring-mvc thymeleaf

当我按下保存按钮时,ajax不起作用。页面重新加载。这是我的indx页面和我的控制器功能。 网址为--- http://localhost:8082/spring-test/index

控制器

@RequestMapping(value = "/saveUser", method = RequestMethod.POST)   
    public String saveUser(@Valid @ModelAttribute("User") User user, BindingResult bindingResult,
             ModelMap model, HttpServletRequest request, RedirectAttributes redirectAttrs) {
        System.out.println("user: " + user.getUserId());
        String type = request.getParameter("update") != null ? request.getParameter("update") : "";
        String delete = request.getParameter("delete") != null ? request.getParameter("delete") : "";
        if (type.equalsIgnoreCase("update") || delete.equalsIgnoreCase("delete")) {
            User userDb = userService.getUserById(user.getUserId());
            user.setUserId(userDb.getUserId());
        }

        if (bindingResult.hasErrors()) {
            System.out.println("=====================error======================" + bindingResult.getFieldErrors());
            return "index";
        }

        if (delete.equalsIgnoreCase("delete")) {
            userService.deleteUser(user.getUserId());
        } else {
            userService.saveUser(user);


        }
        //model.clear();
        model.clear();
        return "redirect:/index";
    }

的index.html

<html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org" class="no-js">

<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />
    <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function() {
                    $('#myTable').DataTable();
                   $('#btnSave').click(function(e) {
                            var dataUser = $("#name").val();
                            var dataPass = $("#pwd").val();
                            var userDdata = {
                                "name": dateUser,
                                "pass": dataPass
                            }

                            $.ajax({
                                type: "POST",
                                url: "/spring-test/saveUser",
                                data: userData,
                                success: function(response) {
                                    alert(1)
                                },
                                error: function(e) {
                                    alert('Error: ' + e);
                                }
                            });

                        }
                    });
    </script>

</head>

<body>
    <div class="container col-sm-12 col-md-12" style="height:20px;background:#85a3e0;">
    </div>
    <div class="container col-sm-12 col-md-12">
        <h3 class="text-center">Super Admin</h3>

        <div class="col-md-4 col-sm-4" style="margin-left: 6%;">

            <form class="form-horizontal" role="form" th:action="@{/saveUser}" th:object="${user}" method="post">
                <div class="form-group">
                    <label class="control-label col-sm-3" for="pwd">Username:</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="name" placeholder="Enter Name" th:field="*{userName}" />
                        <input type="hidden" th:field="*{userId}" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-3" for="pwd">Password:</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="pwd" placeholder="Enter password" th:field="*{password}" />
                    </div>
                </div>

                <div class="form-group">
                    <div class=" col-sm-12 text-right">
                        <button type="submit" class="btn btn-default" name="cancel" value="cancel">Cancel</button>
                        <button id="btnSave" type="submit" class="btn btn-primary" name="save" value="save">Save</button>
                        <button type="submit" class="btn btn-primary" name="update" value="update">Update</button>
                        <button type="submit" class="btn btn-primary" name="delete" value="delete">Delete</button>
                    </div>
                </div>
            </form>
        </div>
    </div>


</body>

</html>

这里的问题是什么。 添加ajax函数后,我的dataTable也没有出现。

3 个答案:

答案 0 :(得分:0)

它没有用,因为你有提交按钮,它直接提交表格。

您可以做什么只需从按钮中删除type="submit"然后尝试。

维诺德

答案 1 :(得分:0)

试试下面的

    <html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org" class="no-js">

    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />
        <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
        <script>
            $(document).ready(function() {
                        $('#myTable').DataTable();
                       $('#btnSave').click(function(e) {
                                var userData = $("#form1").serializeArray();    
                                $.ajax({
                                    type: "POST",
                                    url: "/spring-test/saveUser",
                                    data: userData,
                                    success: function(response) {
                                        alert(1)
                                    },
                                    error: function(e) {
                                        alert('Error: ' + e);
                                    }
                                });

                            }
                        });
        </script>

    </head>

    <body>
        <div class="container col-sm-12 col-md-12" style="height:20px;background:#85a3e0;">
        </div>
        <div class="container col-sm-12 col-md-12">
            <h3 class="text-center">Super Admin</h3>

            <div class="col-md-4 col-sm-4" style="margin-left: 6%;">

                <form class="form-horizontal" role="form" id="form1" th:action="@{/saveUser}" th:object="${user}" method="post">
                    <div class="form-group">
                        <label class="control-label col-sm-3" for="pwd">Username:</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" id="name" placeholder="Enter Name" th:field="*{userName}" />
                            <input type="hidden" th:field="*{userId}" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-3" for="pwd">Password:</label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control" id="pwd" placeholder="Enter password" th:field="*{password}" />
                        </div>
                    </div>


                </form>
 <div class="form-group">
                        <div class=" col-sm-12 text-right">
                            <button type="submit" class="btn btn-default" name="cancel" value="cancel">Cancel</button>
                            <button id="btnSave" type="button" class="btn btn-primary" name="save" value="save">Save</button>
                            <button type="submit" class="btn btn-primary" name="update" value="update">Update</button>
                            <button type="submit" class="btn btn-primary" name="delete" value="delete">Delete</button>
                        </div>
                    </div>
            </div>
        </div>


    </body>

    </html>

答案 2 :(得分:0)

由于您已经为表单提交了一个动作(th:action =&#34; @ {/ saveUser}&#34;),它将直接发送数据,而不是通过AJAX发送。为了使其工作,您需要防止此默认行为,如下所示。

$('#btnSave').click(function(e) {
    e.preventDefault()
    //Then do your stuff
});