我有一个简单的表单,我试图通过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。
发布于 2021-02-09 19:35:15
在submit按钮的onclick属性中,您将触发form元素上的表单提交。这将不会被jQuery捕获,并导致您所看到的表单提交行为。因为它没有指定action,所以它发送一个POST请求到当前的URL,默认情况下也没有method属性。
要解决这个问题,您只需从HTML中删除onclick属性,并完全依赖于使用jQuery附加的不显眼的事件处理程序:
<button type="submit" data-dismiss="modal">Save</button>https://stackoverflow.com/questions/66117987
复制相似问题