JavaScript jQuery 提交按钮问题

标签 javascript jquery xmlhttprequest submit rendering

我有一个问题。我认为这是因为渲染的原因,但我不知道,因为这个主题对我来说是新的。

好的,我有一个简单的表格:

<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/

相关文章:

javascript - 处理异步加载的函数中的无限循环

javascript - jQuery UI onchange 每个循环未按预期工作

javascript - 如何通过 XmlHttpRequest 或 $.ajax 创建并发送文本文件?

javascript - 在资源有限的浏览器(移动)中管理大型数据集的缓存

javascript - 数据更新时的 OwlCarousel 自动高度

javascript - 如何将回发参数从 JS 传递给 VB?

javascript - 将javascript创建的表从一个html传递到另一个html

javascript - Fullcalendar - 调整自定义时间的日历 View 日显示范围

jquery - 使用 jquery 启用表格中带有 rowspan 的文本框

node.js - Node js将pdf缓冲区转换回pdf