Ajax表单提交问题

时间:2021-02-09 11:19:16

标签: jquery ajax forms

我有一个简单的表单,我想通过 ajax 提交。我在 Jquery 中加载并得到了这个简单的形式:

<form id="post_edit">
<input type="hidden" id="id" name="id" value="1">
<input type="text" id="title" name"title" value="This is the title">
<textarea id="body" name="body" rows="3">This is the body</textarea>
<button type="submit" onclick="this.form.submit();" data-dismiss="modal">Save</button>

然后我有这个代码通过ajax提交表单:

$("#post_edit").submit(function(e) {

            e.preventDefault(); 

            var form = $(this);
            var url = 'http://localhost/ajax/posts/' + form.attr('id');

            $.ajax({
                type: "PATCH",
                url: url,
                data: form.serialize(), // serializes the form's elements.
                success: function(data)
                {
                    toastr.success('The post was successfully updated!')
                },
                error:function() {
                    toastr.error('Unable to save changes to the post.<br />Please try again later.')
                }
            });

        });

不知道为什么,但 ajax 提交不起作用,而只是向当前 URL 发送 POST。

1 个答案:

答案 0 :(得分:1)

onclick 按钮的 submit 属性中,您将触发 form 元素上的表单提交。这不会被 jQuery 捕获,并导致您看到表单提交的行为。因为它没有指定 action,所以它会向当前 URL 发送一个 POST 请求,默认情况下同样没有 method 属性。

要解决此问题,您只需从 HTML 中删除 onclick 属性并仅依赖您使用 jQuery 附加的不显眼的事件处理程序:

<button type="submit" data-dismiss="modal">Save</button>