建立JSON发送到PHP使用for循环(也许) [英] Build json to send to php using a for loop (maybe)

查看:130
本文介绍了建立JSON发送到PHP使用for循环(也许)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了一下,但是我可以找到一种方法来使用jQuery构建json,并使用for循环发送给php。我有一个HTML表,我想从每行(我不知道会有多少行/值)构造一个JSON字符串的值,即。 [{row:1,supp_short_code:blah blah ....},{row:2,....} ....]
但我不知道如何保持添加到json数据字符串每次jQuery发现更多的价值,如果这是有道理的??



编辑:



所以,如果我有这个

  $('#submit')。live(' (); 
var $ s $ {'。supp_short_code')。text();
var project_ref = $('。project_ref')。text();
var ($。'om_part_no')。text();
var description = $('。description')。text();
var cost_of_items = $('。cost_of_items')。text );
var cost_total = $('。cost_total')。text();
var dataString ='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,
成功:function()
{
alert(Order Submitted);
}
});
});

那么在这段代码中我需要更改什么(大致)呢?



好的,就像你可以通过截图看到,我使用jQuery来动态添加底部表,当用户点击顶部表中的一行,它的计算总数,他们可以指定他们想要使用哪个供应商。然后,我使用jquery将这些值抓到顶部的jQuery代码的$('submit')位。然后我想把这些值发送到一个PHP页面,将解析接收到的数据插入到一个MySQL数据库,如ID 1产品等价格等公司的总成本£2,产品等等等等总成本£所以一些领域,即总成本和供应商将是相同的,但如果有道理,PHP可能会收到3个不同的产品为同一订单?谢谢!

解决方案

您不需要构建json,只需构建数据数组并使用 .post .get .ajax 。 jQuery将负责为你编码数组:

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

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

您的服务器端代码 $ _ POST 数组将包含:
$ b $ pre $ array('field1'=>'value1','field2'=>'value2',' field3'=>'value3');

对于您的示例,我将重新考虑将数据作为字符串发送,格式化的键/值对。您的服务器端代码可以更容易地决定如何处理它,如果服务器端代码需要字符串的构建方式不同,那么您的JS将不需要重写。

  $。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')。text(),
cost_of_items:$('。cost_of_items')。text(),
cost_total:$('。cost_total')。 text()
}
// ...
});



更新



您可以减少金额通过将您的字段名称放入一个数组中,并添加要包含在数据数组中的任何字段的类名称来进行输入。然后循环遍历每个表行并提取值:

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

var data = [];

//遍历每一行
$('#my-table tr')。each(function(i,tr){
//从这一行中提取字段
var row = {};
for(var f = 0; f row [fields [f]] = $(tr) find('。'+ fields [f])。val();
}

//将行数据追加到数据数组
data.push(row);
});


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 dataString = '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?

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);
});

这篇关于建立JSON发送到PHP使用for循环(也许)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆