添加 Javascript 数组以形成输入

Add Javascript array to form input

我正在用 VueJS 构建一个群组邮件系统,jQuery 用于前端,Laravel 5 用于后端。

我正在使用 AJAX 调用来检索基于组、机构或所有活跃用户的用户列表。然后,用户可以根据 DOM (VueJS data) 中的这些结果删除地址,并手动添加新地址。

该表单包含一个文件,所以我不能(或不想,基于兼容性问题)使用 AJAX 调用发送表单数据。问题是我需要在用户提交表单时将电子邮件地址列表与表单一起发送。

这里是Javascript。最相关的部分是 serializeRecipients 方法,我将每个电子邮件地址附加到隐藏的表单字段:

var vm = new Vue({
    el: '#emailContainer',
    data: {
        recipients: [
            {
               name: "Joe Smith",
               email: "joe@demo.com"
            }
        ],
        individualRecipients: [],
        manualRecipient: null,
        validation: {
            email: true
        }
    },

    methods: {
        //
        serializeRecipients: function() {
            var recipientAddresses = [];
            var individualRecipientAddresses = [];
            $.each(this.recipients, function (k, recipient) {
                recipientAddresses.push(recipient['email']);
            });
            $.each(this.individualRecipients, function(k, recipient) {
                individualRecipientAddresses.push(recipient);
            });

            $("#recipientsInput").val(recipientAddresses);
            $("#individualRecipientsInput").val(individualRecipientAddresses);
        }
    }
});

在我使用的表单元素上 v-on="submit: serializeRecipients"。这会生成此表单输出:someone@demo.com, someoneelse@demo.com,然后我使用 PHP 的 explode() 函数将其转换为数组。

这一切都有效,但我想知道是否有更好的方法来完成它。如有任何建议,我们将不胜感激!

您可以将数组连接成一个字符串,然后在服务器上解析它。

$("#recipientsInput").val(recipientAddresses.join(','));
$("#individualRecipientsInput").val(individualRecipientAddresses.join(','));

所以:

['me@somewhere.com', 'you@somewhereelse.com', 'him@somewhere.com']

会变成:

'me@somewhere.com,you@somewhereelse.com,him@somewhere.com'

然后在服务器上您可以用逗号分隔该字段。