javascript - 如何在 Sweet Alert 2 Promise 中传递数组

标签 javascript arrays promise sweetalert2

我正在使用SweetAlert2显示效果很好的表单,但是我最近遇到了一个无法解决的问题,我已经浪费了几天时间试图在谷歌上找到解决方案。

我正在使用 PHP 动态构建一个由 Sweet Alert 加载的表单。该表单包含多个具有相同名称/ID 的复选框。我有 3 组多个复选框,因为它是动态表单,所以我不知道每组中有多少个复选框。

复选框集名为invoice_detailsinvoice_hoursinvoice_materials。每组可能没有复选框,也可能有十个或更多。但每组复选框具有相同的名称,因此invoice_details 组均命名为invoice_details。

如何将每组复选框的结果放入数组中并将它们传递给 Promise,以便我可以在 php 页面中处理表单?

<script type="text/javascript">
    // SCRIPT TO ADD INVOICE

    //Warning Message with function
    $(document).on('click', '#addinvoice', function(){
        swal({
    title: 'Generate New Invoice',
    html: '<?php echo tm_generate_invoice_form( $post->ID ) ?>',
    showCancelButton: true,
    confirmButtonText: 'Submit',
    showLoaderOnConfirm: true,
    buttonsStyling: true,
    confirmButtonClass: 'btn btn-primary btn-lg',
    cancelButtonClass: 'btn btn-lg',
    preConfirm: function () {
    return new Promise(function (resolve) {
      resolve([
        $('#invoice_number').val(),
        $('#invoice_details').val(),
        $('#invoice_hours').val(),
        $('#invoice_materials').val(),
        $('#invoice_custom_message').val(),
        $('#jobid').val(),
        $('#tm_add_invoice').val()
      ])
    })
  }
}).then(function(result){
            swal(
                "Invoice Created!",
                "Invoice now ready to be sent to customer.",
                "success"
            );
            $.ajax({
            type: 'post',
            url: '<?php echo admin_url( 'admin-ajax.php' ) ?>',
            data: {
                action: 'tm_add_invoice',
                invoice_number: result[0],
                invoice_details: result[1][0],
                invoice_hours: result[2][0],
                invoice_materials: result[3][0],
                invoice_custom_message: result[4],
                jobid: result[5],
                tm_add_invoice: result[6]
            },
            success: function(data){

                $('#invoices').html(data);

            },
            error: function(e){
                 alert("error " + e);
                 console.log(e);
            }
            });
        });
    });
</script>

最佳答案

忘记 ID。使用格式为 name="xxx[]"name 属性构建表单。

例如:

<form id="myForm">
    <input name="invoice_number" value="invoice_no_000" /><br/>
    <br/>
    <input type="checkbox" name="invoice_details[]" value="abc" /><br/>
    <input type="checkbox" name="invoice_details[]" value="bcd" /><br/>
    <br/>
    <input type="checkbox" name="invoice_hours[]" value="cde" /><br/>
    <input type="checkbox" name="invoice_hours[]" value="def" /><br/>
    <input type="checkbox" name="invoice_hours[]" value="efg" /><br/>
    <input type="checkbox" name="invoice_hours[]" value="fgh" /><br/>
    <br/>
    <input type="checkbox" name="invoice_materials[]" value="ghi" /><br/>
    <input type="checkbox" name="invoice_materials[]" value="hij" /><br/>
    <input type="checkbox" name="invoice_materials[]" value="ijk" /><br/>
    <input type="checkbox" name="invoice_materials[]" value="jkl" /><br/>
    <input type="checkbox" name="invoice_materials[]" value="klm" /><br/>
    <input type="checkbox" name="invoice_materials[]" value="lmn" /><br/>
    <input type="checkbox" name="invoice_materials[]" value="mno" /><br/>
    <br/>
    <!-- other fields as necessary -->
    <br/>
    <input type="submit" />
</form>

每个集合中的元素不一定是相邻的。交错元素将以相同的方式序列化。

现在您可以简单地使用 jQuery 的 .serialize() 序列化表单。 .

'preConfirm': function () {
    return Promise.resolve($('#myForm').serialize());
}

正如文档所说:

Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

因此,根据选中的复选框,最终的序列化(带有添加的换行符)可能是:

invoice_number%5B%5D=invoice_no_000&
invoice_details%5B%5D=bcd&
invoice_hours%5B%5D=cde&
invoice_hours%5B%5D=fgh&
invoice_materials%5B%5D=hij&
invoice_materials%5B%5D=jkl&
invoice_materials%5B%5D=klm&
invoice_materials%5B%5D=lmn

在服务器端,PHP 将看到的数据为:

  • $_POST['invoice_number'] : 'invoice_no_000'
  • $_POST['invoice_details'] : ['bcd']
  • $_POST['invoice_hours'] : ['cde', 'fgh']
  • $_POST['invoice_materials'] : ['hij', 'jkl', 'klm', 'lmn']

我怀疑这就是所需要的。

关于javascript - 如何在 Sweet Alert 2 Promise 中传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49998291/

相关文章:

javascript - 如何更改 jquery promise 链中的解析值

javascript - 如何中止获取请求并立即开始新的请求?

javascript - 匿名函数,添加参数

javascript - Backbone .js。正确设置更改事件

javascript - 如何知道异步调用是否完成? (黑客新闻评论)

c - 生成四字母字符数组时出错

Javascript 函数用于返回数组中长度超过定义数量的字符串

javascript - 如何使用 javascript 检测特定页面加载?

javascript - 签名板无法在移动设备上使用

javascript - 在 Firebase 中管理聊天 channel 的最佳方式