我有一个问题。我认为这是因为渲染的原因,但我不知道,因为这个主题对我来说是新的。
好的,我有一个简单的表格:
<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>
现在我想使用 jQuery 捕获该提交,例如:
$('[type=submit]').submit(function(e) {
e.preventDefault();
var formHtml = $(this).parent().html();
$.ajax({
..all these options..,
beforeSend: function(xhr) {
$('form').html("sending mail");
},
success: function(data) {
$('form').html(formHtml); // I think here's the problem...
}
});
});
好的,该代码运行得非常好。它做了它应该做的事情。但是,如果我想发送第二个请求,提交按钮将不再按预期工作。它尝试使用默认操作发送表单,尽管我阻止了这一点 - 至少我是这么想的。
我确实使用过谷歌,但我什至不知道如何解释我的问题。
希望有人能帮助我,非常感谢!
问候
最佳答案
您可以使用:代替.html():
.clone(true): Create a deep copy of the set of matched elements.
.replaceWith(): Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
如果附加到提交按钮,该事件必须是点击;如果附加到表单,该事件必须是提交。
代码片段:
$('[type=submit]').on('click', function (e) {
e.preventDefault();
var formHtml = $(this).closest('form').clone(true);
$.ajax({
dataType: "json",
url: 'https://api.github.com/repos/octocat/Hello-World',
beforeSend: function (xhr) {
$('form').html("sending mail");
},
success: function (data) {
console.log('Success');
$('form').replaceWith(formHtml); // I think here's the problem...
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>
关于JavaScript jQuery 提交按钮问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44605064/