简体   繁体   中英

How to send js array to servlet using ajax?

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?

To get the form yao@a.com, yao@b.com you can use the Array.join(delim) function.

Ex:

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

However, I'd say you'd want to keep the emails as an array and do the follow:

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

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

This will allow you to parse the JSON object coming back. Instead of having a string in emails you'll have an array. Not sure of your back-end but this may be an easier approach if you are already able to parse the JSON.

try to add header to ajax configuration:

headers: {'Content-type' : "application/json; charset=utf-8"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM