jQuery表单提交没有刷新

时间:2017-02-17 15:10:14

标签: jquery forms

我有一个表单,我希望将数据提交但不刷新页面。我已添加此代码,该代码停止刷新但也停止了提交。使用preventDefault()时有没有办法做到这一点?

    $("editUserForm").on('submit', function (e) {
                e.preventDefault();

                $.ajax({
                    url: this.action,
                    type: 'POST',
                    data: $("editUserForm").serialize()

                })

            });

2 个答案:

答案 0 :(得分:1)

您的选择器只会选择editUserForm类型的元素,如:

<editUserForm></editUserForm>

您可能想要选择by its id

表单
$("#editUserForm")

<form id="editUserForm"></form>

by its name attribute

$("form[name='editUserForm']")

<form name="editUserForm"></form>

答案 1 :(得分:0)

以下是使用没有刷新页面的ajax提交表单的代码。

                <form name="addstudent" id="addstudent" action="add.php" method="post">

                    <fieldset><legend>Add student to tutoring list</legend>
                    <div><label for="studentid">ID number</label><input type="text" name="studentid" id="studentid"></div>


                    <div><label for="assignment">Tutoring assignment</label><select name="assignment" id="assignment">
                    <option value="">Please select an assignment</option>
                    <option value="att">Activity Time</option>
                    <option value="acc">ACC</option>
                    <option value="tech">ACC Tech </option>
                    <option value="ast">After School</option>
                    </select></div>

                    <div><label for="teacher">Assigning teacher</label><input type="text" name="teacher" id="teacher"></div>

                    <input type="submit" name="submit" value="submit" id="submit">
                    </fieldset>
                    </form>

                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
                    <script>
                    $(document).ready(function(){

                        $("body").on('submit',"#addstudent" ,function (e) {
                            e.preventDefault();

                            $.ajax({
                                url: $( '#addstudent' ).attr( 'action' ),
                                type: 'POST',
                                data: $("#addstudent").serialize(),
                                success: function(data) {
                                    console.log(data);
                                }
                            });
                        });
                      });      

                    </script>