最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sending an array in POST body - Stack Overflow

programmeradmin0浏览0评论

Im trying to send an array to my Node/MongoDB server via and AJAX POST request. The body also contains other variables. Here is the client side JS code:

function setupForm(){
    $("#add").submit(function(event) {
        event.preventDefault();
        var name = $("#name").val();
        var logo = $("#logo").val();
        var phone = $("#phone").val();
        var email = $("#email").val();
        var address = $("#address").val();
        var postcode = $("#postcode").val();
        var openingHours = $("#openingHours").val();
        var loc = [44, 44];

        $.ajax({
            type: "POST",
            url: "http://localhost:3000/services",
            data: "name=" + name + "&logo=" + logo + "&phone=" + phone + "&email=" + email + "&address=" + address + "&postcode="+ postcode +"&openingHours=" + openingHours + "&loc=" + loc,
            success: function(){alert('success');}
        });
    });
}

And here is the the server side code:

exports.addWine = function(req, res) {
    var wine = req.body;
    console.log('Adding wine: ' + JSON.stringify(wine));
    db.collection('services', function(err, collection) {
        collection.insert(wine, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
}

It adds it to the database but in this format. I would like it in an array:

"postcode" : "ugh",
"openingHours" : "fhgfh",
"loc" : "44,44"

Im trying to send an array to my Node/MongoDB server via and AJAX POST request. The body also contains other variables. Here is the client side JS code:

function setupForm(){
    $("#add").submit(function(event) {
        event.preventDefault();
        var name = $("#name").val();
        var logo = $("#logo").val();
        var phone = $("#phone").val();
        var email = $("#email").val();
        var address = $("#address").val();
        var postcode = $("#postcode").val();
        var openingHours = $("#openingHours").val();
        var loc = [44, 44];

        $.ajax({
            type: "POST",
            url: "http://localhost:3000/services",
            data: "name=" + name + "&logo=" + logo + "&phone=" + phone + "&email=" + email + "&address=" + address + "&postcode="+ postcode +"&openingHours=" + openingHours + "&loc=" + loc,
            success: function(){alert('success');}
        });
    });
}

And here is the the server side code:

exports.addWine = function(req, res) {
    var wine = req.body;
    console.log('Adding wine: ' + JSON.stringify(wine));
    db.collection('services', function(err, collection) {
        collection.insert(wine, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
}

It adds it to the database but in this format. I would like it in an array:

"postcode" : "ugh",
"openingHours" : "fhgfh",
"loc" : "44,44"
Share Improve this question asked Apr 21, 2016 at 21:13 spogebob92spogebob92 1,4844 gold badges23 silver badges33 bronze badges 1
  • Use jQuery's serialize() function. – angelcool Commented Apr 21, 2016 at 21:17
Add a ment  | 

3 Answers 3

Reset to default 2

As mentioned, use serializeArray(). To add your extra parameter, just append it to the array as shown below.

function setupForm(){
    $("#add").submit(function(event) {
        event.preventDefault();

        var data = $(this).serializeArray();
            // add extra parameters (don't forget brackets)
            data.push({ name: 'loc[]', value: 44 });
            data.push({ name: 'loc[]', value: 44 });

        $.ajax({
            type: "POST",
            url: "http://localhost:3000/services",
            data: data,
            success: function() {
               alert('success');
            }
        });
    });
}

If you want to continue using your method of just building the query string, you would have to add &loc[]=44&loc[]=44 but it is better in the long run to just use one of the serialize functions.

Given the data you are using, I would advise sending the data in the POST requests' body. This will retain the datatypes (array, bools, etcs) thanks to JSON.

$.post("http://localhost:3000/services", {
        name: $("#name").val(),
        loc: [44, 44]
        ...etc
    }, function(){alert('success');}
);

Backend should work fine without alterations. You might need to add body-parser to your middleware stack. The body-parser middleware will transform the body into a javascript object that you can push right into your database.

Take a look at jQuery's .serialize() and .serializeArray(). They should be able to do what you're looking for.

发布评论

评论列表(0)

  1. 暂无评论