【问题标题】:Javascript Sweetalert is sending form multiple timesJavascript Sweetalert 多次发送表单
【发布时间】:2017-11-23 13:19:59
【问题描述】:

我的以下 javascript 函数正在多次发送表单。 同时发布 4 到 9 个帖子,我现在无法获取。

函数如下:

function formModal(url, id, type, text, send_type) {
    $(document).ready(function () {
        $('#' + id).on('submit', function (e) { //id of form
            $.ajax({
                url: url, // PHP file
                data: $(this).serialize(),
                type: send_type,
                success: function (data) {
                    console.log(data);

                    // Success Alert
                    swal({
                        html: true,
                        title: text,
                        type: type,
                        timer: 1500,
                        showConfirmButton: false
                    });
                    setTimeout(function () {
                        // Refresh after 2 seconds
                        window.location.href = "";
                    }, 2200);
                },
                error: function (data) {
                    //Error Alert 
                    swal("Oops...", "Something went wrong :(", "error");
                }
            });
            e.preventDefault(); //This is to Avoid Page Refresh and Fire the Event "Click"
        });
    });
};

该函数将在 HTML/PHP 脚本中使用:

   <script> formModal('/dashboard_scripts/module/wiki/edit_wiki_article.php', 'edit_article', 'success', 'Artikel wurde gespeichert', 'GET') </script>

【问题讨论】:

  • 为什么要在函数中编写 (document).ready?
  • 如果对您有用,请选择答案。

标签: javascript jquery forms sweetalert sweetalert2


【解决方案1】:

你在代码中做了什么,为什么 $(document).ready()function formModal() 内然后在 $(document).ready() 内绑定 submit 处理程序,这意味着每次调用 formModal() 时,你正在绑定一个提交事件处理程序,这就是表单多次提交的主要原因。您应该从函数中删除提交处理程序并进行简单的 ajax 调用或更改

$('#'+id).on('submit', function (e) {

$('#'+id).off('submit').on('submit', function (e) {

Sweet Alert 与你的表单的多次提交无关

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    相关资源
    最近更新 更多