开发者

Build json to send to php using a for loop (maybe)

I've googled around, but i can find a way to build json with jQuery and send it to php using a for loop. I have a html table, and i want to take values from each row (i dont know how many rows/values there will be) construct a json string, ie. [{"row": 1, "supp_short_code" : blah blah....}, {"row": 2, ....} ....] but i dont know how to keep adding to the json datastring each time jQuery finds more values if that makes sense??

EDIT:

So if i have this

$('#submit').live('click',function(){ 
                    var supp_short_code=$('.supp_short_code').text();
                    var project_ref=$('.project_ref').text();
                    var om_part_no=$('.om_part_no').text();
                    var description=$('.description').text();
                    var cost_of_items=$('.cost_of_items').text();
                    var cost_total=$('.cost_total').text();
                    var data开发者_StackOverflow中文版String = 'string=//' + supp_short_code + '//' + project_ref + '//' + om_part_no + '//' + description + '//' + cost_of_items + '//' + cost_total

                    $.ajax
                        ({
                        type: "POST",
                        url: "order.php",
                        data: dataString,
                        cache: false,
                        success: function()
                            {
                                alert("Order Submitted");
                            }
                        });
                });

So what (roughly) would i need to change in this code?

Build json to send to php using a for loop (maybe)

Ok, so as you can see by the screenshot, i'm using jquery to dynamically add the bottom table when a user click a row from the top table, its calculating totals and they can specify which supplier they want to use. I'm then using jquery to grab these values into the $('submit') bit of jquery code at the top. I then want to send these values to a php page that will somehow parse the received data at insert it into a mysql db, as something like "id 1 product blah price blah supplier blah total cost £x, id 2 product blah2 price blah2 supplier blah total cost £x" so some fields, ie the total cost and supplier will be the same, but the php might be receiving 3 different products for the same order if that makes sense? Thanks!


You don't need to build the json, just build the data array and send it with .post, .get or .ajax. jQuery will take care of encoding the array for you:

var data = {};

for (var i = 0; i < 3; ++i) {
   data['field' + i] = 'value' + i;
}

$.post ('http://mysite.com/page', data, function() { alert('succes!'); });

Your server-side code's $_POST array will containing:

array( 'field1' => 'value1', 'field2' => 'value2', 'field3' => 'value3'); 

For your example, I would reconsider sending the data as a string and instead send the data as well-formated key/value pairs. Your server-side code can more easily decide what to do with it, and your JS won't require a rewrite if the server-side code needs the string to be built differently.

$.ajax ({
  type: "POST",
  url:  "order.php",
  data: {
   supp_short_code: $('.supp_short_code').text(),
   project_ref:     $('.project_ref').text(),
   om_part_no:      $('.om_part_no').text(),
   description:     $('.description').text(),
   cost_of_items:   $('.cost_of_items').text(),
   cost_total:      $('.cost_total').text()
  }
  //...
});

Update

You could reduce the amount of typing by throwing your field names into an array, and appending the class name of any fields you want to include in the data array. Then loop over each of your table rows and extract the values:

var fields = [ 'supp_short_code', 'project_ref', 'om_part_no',
  'description', 'cost_of_items', 'cost_total'];

var data = [];

// loop over each row
$('#my-table tr').each(function (i, tr) {
  // extract the fields from this row
  var row = {};
  for (var f = 0; f < fields.length; ++f) {
    row[fields[f]] = $(tr).find('.' + fields[f]).val();
  }

  // append row data to data array
  data.push(row);
});


Here's a quick way to grab data from your table, and format it as an array:

var data_to_send = $('#yourtable').find('tr').map( function(idx){
  return [ 
      'row': idx+1,
      'supp_short_code' : $(this).find('td').eq(2).text(), 
      'something_else' : $(this).find('td').eq(3).text() // etc
  ];      
}).get();

Now you have data_to_send, an array formatted similarly to the example in your question. As @meagar points out, you can simply post this to the server with .ajax() et al., and allow jQuery to automatically handle the encoding. Something like this:

$.ajax ({
  type: 'post',
  url:  'your_script',
  data: data_to_send
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜