weixin_33701294 2016-04-21 21:13 采纳率: 0%
浏览 49

在POST正文中发送数组

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"
  • 写回答

3条回答 默认 最新

  • 胖鸭 2016-04-21 21:19
    关注

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

    评论

报告相同问题?