0

I have a textarea where a user can enter 1 or more emails on there, each email separated by comma.

My js code:

    var emails = $("#emails").val().split(",");

    if (emails.length == 0)
    {
        window.alert("Enter an email address.");
        $("#emails").focus();
        return;
    }

    var valid = validateEmails(emails);
    var goodEmails = valid[0];
    var badEmails = valid[1];
    var json = JSON.stringify(goodEmails);

    $.ajax
    ({
        url: "/mfa/service/initiate_user",
        type: "POST",
        data: {"emails" : json},

The data I see:

["yao@a.com","yao@b.com]

What I was hoping for:

yao@a.com, yao@b.com

The way I would handle it in the backend is basically stripping out the "[ ]" from it then stripping out the quotes from each email.

What is the proper way to send the emails to backend without those silly brackets and quotes?

4

2 回答 2

3

要获取表格yao@a.com, yao@b.com,您可以使用该Array.join(delim)功能。

前任:

var emails = ["yao@a.com", "yao@b.com"];
var email_string = emails.join(", ");
// email_string:
// yao@a.com, yao@b.com

但是,我会说您希望将电子邮件保留为数组并执行以下操作:

var valid = validateEmails(emails);
var goodEmails = valid[0];
var badEmails = valid[1];

$.ajax
({
    url: "/mfa/service/initiate_user",
    type: "POST",
    data: {"emails" : goodEmails},
...

这将允许您解析返回的 JSON 对象。emails您将拥有一个数组,而不是一个字符串。不确定您的后端,但如果您已经能够解析 JSON,这可能是一种更简单的方法。

于 2013-03-04T22:39:34.583 回答
0

尝试将标头添加到 ajax 配置:

标头:{'Content-type':“应用程序/json; charset=utf-8”}

于 2013-03-04T22:42:23.737 回答