简体   繁体   中英

How to build a javascript array to be converted to JSON?

I have a function that should

  1. collect all input data in an array
  2. put that array in JSON format (to be used as ajax post data)

Here's what I have, which seems like it should work, but when I log the stringified version, all I get is [].

function get_data_from_form() {
    var data = [];
    var inputs = $('form').find('input');

    $.each(inputs, function (index, value) {
        var name = $(this).attr('name');

        data[name] = value; // How should this change?

    });
    console.log('stringified data: ' + JSON.stringify(data)); // -> []
}

The desired output should be something like: "{ fname: 'turd', lname: 'ferguson' }"

What am I doing wrong? Would it be easier to just make a string and concat the name/value pairs?

You should define a object, not an array

var data = {};

data[name] = value;

Your value extraction field is wrong - in the .each call the value parameter is the current element, not its value. Also, you need to capture the fields in a key/value store, ie an Object instead of an Array . Try this, instead:

var data = {};  // NB: *not* an array

$('form :input').each(function() {
    data[this.name] = this.value;
});

See http://jsfiddle.net/alnitak/hsy2xd5L/

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