javascript 使用jquery使用选定的列从html表创建json对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11043221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create json object from html table using selected colums using jquery
提问by gerpaick
i was wondering how to parse html table to get json object that i can send via $.post with jquery.
我想知道如何解析 html 表以获取 json 对象,我可以使用 jquery 通过 $.post 发送该对象。
i have a table
我有一张桌子
<table id="Report">
<thead>
<tr>
<th>Kod</th>
<th>Nazwa</th>
<th>Ilo??</th>
<th>Netto / 1szt.</th>
<th>Suma brutto</th>
</tr>
</thead>
<tbody>
<tr>
<td>00171 </td>
<td>S?UP 50/1800 PO?REDNI(P) </td>
<td>5</td><td>97.00 PLN </td>
<td>394.31 PLN </td>
</tr>
<tr>
<td>00172</td>
<td>S?UP 50/1800 NARO?NY(P)</td>
<td>1</td><td>97.00 PLN</td>
<td>78.86 PLN</td>
</tr>
<tr>
<td>00173 </td>
<td>S?UP 50/1800 KO?COWY(P) </td>
<td>1</td><td>97.00 PLN </td>
<td>78.86 PLN</td>
</tr>
</tbody>
<tfoot style="font-weight: bold;">
<tr>
<th colspan="3" style="text-align: right;">Razem netto: 1955.85 PLN</th>
<th colspan="2" style="text-align: right;">Razem brutto: 2405.69 PLN</th>
</tr>
</tfoot>
</table>
and what i need is json object in this format (first <td>
and third <td>
):
我需要的是这种格式的 json 对象(第一个<td>
和第三个<td>
):
[{"00171":5},
{"00172":1},
{"00173":1}
]
and that i can send it via
我可以通过
$.post(
"print.php",
{json: myjsonvar},
"json"
);
any idea how to do that?
知道怎么做吗?
thanks
谢谢
回答by Kevin Ennis
var json = [];
$('#Report').find('tbody tr').each(function(){
var obj = {},
$td = $(this).find('td'),
key = $td.eq(0).text(),
val = parseInt( $td.eq(2).text(), 10 );
obj[key] = val;
json.push(obj);
});
回答by broesch
How about:
怎么样:
var myjsonvar=[];
$('#Report tbody tr').each(function(){
var data={};
var tr=$(this);
data[tr.find('td:first-child').text()]=tr.find('td:nth-child(3)').text();
myjsonvar.push(data);
});
回答by mVChr
回答by d_inevitable
Why json, if you are in js already? Just create a simple object:
如果您已经在使用 js,为什么要使用 json?只需创建一个简单的对象:
var data = {};
$("#Report tbody tr").each(function() {
data[$(this).children("td:eq(0)").text()] = $(this).children("td:eq(2)").text();
});
$.post("print.php", data);
Setting type to json in $.post
defines the server response to be json
, not the send data!
将类型设置为 json in$.post
将服务器响应定义为json
,而不是发送数据!
回答by The Alpha
var objArray=[];
$('table#Report tbody tr').each(function(i){
var row=$(this);
obj={};
obj[$('td', row).eq(0).text()]=$('td', row).eq(2).text();
objArray.push(obj);
});