简体   繁体   中英

Sending an array of objects to server via ajax (JQuery)

I have a series of entries retrieved from an html table.

Eg (1, 123), (1,234), (2, 134) …etc

I want to send these via JQuery ajax call to the server but I am not sure how to create the corresponding json call.
How can I do this?

I don't know how to form the array. I know I should use something like:

$.ajax({
  url: 'path/getdetails.html',
   data : {
       'a'     : value,
       'b'    : value,                                                                                                                                      
    }, 
    type: 'POST',
    dataType: 'json',

This is my table

<table id="students" border="1">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Grade</th>
        </tr>
    </thead>
    <tbody>
        <tr class="student">
            <td>Oscar</td>
            <td>23</td>
            <td>16.5</td>        
        </tr>
        <tr class="student">
            <td>Antonio</td>
            <td>32</td>
            <td>14</td>        
        </tr>
        <tr class="student">
            <td>Jessica</td>
            <td>21</td>
            <td>19</td>        
        </tr>
    </tbody>
</table>​​​​​​

and my java script look like this

     function send() {
            var value = $('#students tr:has(td)').map(function(i, v) {
    var $td =  $('td', this);
        return {
                 id: ++i,
                 name: $td.eq(0).text(),
                 age: $td.eq(1).text(),
                 grade: $td.eq(2).text()               
               }
}).get();
            $.ajax({
                url: '/test/PersonSubmit',
                type: 'post',
                dataType: 'json',
                data:JSON.stringify(values),
                success: function (data) {
                    $('#target').html(data.msg);
                },

            });
        }  

hope this will help you

Lets say your array of objects is

var postData =  [{"key1": 123}, {"key2": 234}, {"key3": 134}]

Use JSON.stringify for your data and content type of application/json in your ajax call.

Like this

contentType: 'application/json'
data: JSON.stringify(postData)

Hope that helps :)

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