json 到 php/javascript 中的 html 表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22119387/
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
json to html table in php/javascript
提问by user3332475
i have a json file like this:
我有一个像这样的json文件:
{
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 ",
signingDate: "28-02-2014"
},
i need to show it in a table like this:
我需要在这样的表格中显示它:
<table>
<tr>
<td><strong>Data de publica??o</strong></td>
<td><strong>Empresa Contratada</strong></td>
<td><strong>Empresa que Contratou</strong></td>
<td><strong>ID</strong></td>
<td><strong>Objecto adquirido</strong></td>
<td><strong>Pre?o Contratual</strong></td>
<td><strong>Data do Contrato</strong></td>
</tr>
</table>
how i do it in PHP or javascript?
我如何在 PHP 或 javascript 中做到这一点?
thank you very much people ;)
非常感谢你们;)
回答by Kristian Barrett
Here is a JSFiddle that shows how to print the data in your object:
这是一个 JSFiddle,显示了如何在对象中打印数据:
And the code:
和代码:
HTML
HTML
<table id="table">
<tr>
</tr>
</table>
JAVASCRIPT
爪哇脚本
var object = {
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 ",
signingDate: "28-02-2014"
};
for (var prop in object) {
// important check that this is objects own property
// not from prototype prop inherited
if(object.hasOwnProperty(prop)){
var td = document.createElement("td");
var strong = document.createElement("strong");
var text = document.createTextNode(prop + " - " + object[prop]);
strong.appendChild(text);
td.appendChild(strong);
document.getElementById("table").appendChild(td);
}
}
EDIT UPDATE TO angus_thermopylae:
编辑更新到 angus_thermopylae:
I have updated the JSFiddle to show the concept: http://jsfiddle.net/4PVr5/12/
我已经更新了 JSFiddle 来展示这个概念:http: //jsfiddle.net/4PVr5/12/
Then you can have as many properties on the object you want but only print the ones you defined and in the order you defined. You just add a text string and then you got another print.
然后你可以在你想要的对象上拥有尽可能多的属性,但只打印你定义的属性和你定义的顺序。您只需添加一个文本字符串,然后您就会得到另一个打印件。
EDIT UPDATE: I updated the code to follow the table headers. Now it adds them directly and also handles objects with too few properties.
编辑更新:我更新了代码以遵循表标题。现在它直接添加它们并且还处理属性太少的对象。
HTML
HTML
<table id="table">
<thead>
<th id="publicationDate"></th>
<th id="contracted"></th>
<th id="contracting"></th>
<th id="id"></th>
<th id="objectBriefDescription"></th>
<th id="initialContractualPrice"></th>
<th id="signingDate"></th>
</thead>
<tbody>
</tbody>
</table>
JAVASCRIPT
爪哇脚本
var orderedObject = {
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 ",
signingDate: "28-02-2014"
};
var unorderedObject = {
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 ",
signingDate: "28-02-2014",
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
};
var toManyPropertiesObject = {
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 ",
signingDate: "28-02-2014",
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
newProp: "ignored",
newProp1: "ignored",
newProp2: "ignored",
};
var toFewPropertiesObject = {
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 ",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
};
printObjectInTable(orderedObject, "table");
printObjectInTable(unorderedObject, "table");
printObjectInTable(toManyPropertiesObject, "table");
printObjectInTable(toFewPropertiesObject, "table");
function printObjectInTable(objectToIterate, tableID) {
var thChildren = document.getElementById(tableID).getElementsByTagName("th"),
childrenLength = thChildren.length,
tr = document.createElement("tr");
for (var i = 0; i < thChildren.length; i++) {
var th = thChildren[i];
// important check that this is objects own property
// not from prototype prop inherited
var td = document.createElement("td");
if (objectToIterate.hasOwnProperty(th.id)) {
td.appendChild(document.createTextNode(objectToIterate[th.id]));
}
tr.appendChild(td);
}
document.getElementById(tableID).getElementsByTagName("tbody")[0].appendChild(tr);
}
回答by meda
Here is how you can do it in PHP:
以下是您可以在 PHP 中执行此操作的方法:
$json=file_get_contents("http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)");
$data = json_decode($json);
//var_dump($data);
echo "<table>
<tr>
<td><strong>Data de publica??o</strong></td>
<td><strong>Empresa Contratada</strong></td>
<td><strong>Empresa que Contratou</strong></td>
<td><strong>ID</strong></td>
<td><strong>Objecto adquirido</strong></td>
<td><strong>Pre?o Contratual</strong></td>
<td><strong>Data do Contrato</strong></td>
</tr>";
foreach($data as $object):?>
<tr>
<td><strong><?php echo $object->{'publicationDate'}?></strong></td>
<td><strong><?php echo $object->{'contracted'}?></strong></td>
<td><strong><?php echo $object->{'contracting'}?></strong></td>
<td><strong><?php echo $object->{'id'}?></strong></td>
<td><strong><?php echo $object->{'objectBriefDescription'}?></strong></td>
<td><strong><?php echo $object->{'initialContractualPrice'}?></strong></td>
<td><strong><?php echo $object->{'signingDate'}?></strong></td>
</tr>
<?php endforeach;
echo "</table>";
?>
回答by Suman Bogati
Accoding to your answer on comment, you are using
根据您对评论的回答,您正在使用
$('table#tbl TBODY').append(
for append the data into table,
将数据附加到表中,
But you should use
但你应该使用
$('table#tbl').append(
Other code is fine
其他代码没问题
Also you have to run your code into web server.
此外,您必须将代码运行到 Web 服务器中。
回答by angus_thermopylae
A per-row conversion will work something like this (low level and not doing anything fancy):
每行转换将像这样工作(低级别并且不做任何花哨的事情):
//with jdata as the object below
{
publicationDate: "28-02-2014",
contracted: "Servicash - Equipamentos Electrónicos, Lda.",
contracting: "Banco de Portugal",
id: 994738,
objectBriefDescription: "Consumíveis de papel para tratamento de dinheiro",
initialContractualPrice: "12.945,50 ",
signingDate: "28-02-2014"
}
function tablize(jdata) {
var trow = "<tr>";
trow += "<td>"+jdata.publicationData+"</td>";
trow += "<td>"+jdata.contracted+"</td>";
trow += "<td>"+jdata.contracting+"</td>";
trow += "<td>"+jdata.id+"</td>";
trow += "<td>"+jdata.objectBriefDescription+"</td>";
trow += "<td>"+jdata.initialContractualPrice+"</td>";
trow += "<td>"+jdata.signingDate+"</td>";
trow += "</tr>"
return trow;
}
Now your issue is getting it in the table. Assuming you have the ability to adjust (slightly) the table structure, I would recommend setting up your table like so:
现在你的问题是把它放在桌子上。假设你有能力调整(稍微)表格结构,我建议你像这样设置你的表格:
<table>
<thead>
<tr>
<th><strong>Data de publica??o</strong></th>
<th><strong>Empresa Contratada</strong></th>
<th><strong>Empresa que Contratou</strong></th>
<th><strong>ID</strong></th>
<th><strong>Objecto adquirido</strong></th>
<th><strong>Pre?o Contratual</strong></th>
<th><strong>Data do Contrato</strong></th>
</tr>
</thead>
<tbody id="cdata"></tbody>
</table>
Then, you just need a function to either iterate through all the data and add the accumulated rows, or append the newly created row to the element:
然后,您只需要一个函数来遍历所有数据并添加累积的行,或者将新创建的行附加到元素:
Assuming you'll get this data as an array:
假设您将这些数据作为数组获取:
function fillTable(contractarray) {
var tblrows = "";
if (contractarray) {
for (var i=0;i<contractarray.length;i++) {
tblrows += tablize(contractarray[i]);
}
}
//appropriate method to set the table body--using jQuery for brevity
$("#cdata").html(tblrows);
}
If you don'thave the ability to adjust the table html, then you'll have to "find" the table in the DOM structure another way and either recreate the entire thing (headers included) or adjust it by clearing/adding rows appropriately.
如果您没有能力调整表格 html,那么您必须以另一种方式在 DOM 结构中“找到”表格,然后重新创建整个事物(包括标题)或通过适当地清除/添加行来调整它.
Either way, the tablize(jdata) function will work, and the second function will need to be adjusted accordingly.
无论哪种方式,tablize(jdata) 函数都可以工作,第二个函数需要相应调整。
To pull it altogether (with the url that the requestor supplied:
完全拉取它(使用请求者提供的网址:
var dataurl = "http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)";
$.getJSON(dataurl, function(data) { tablize(data)});
That kicks off the request, passes the data to the tablize() function, and fills the rows. A small (but good) side effect is that if no data is returned, the table empties, showing that we got nothing back.
这会启动请求,将数据传递给 tablize() 函数,并填充行。一个小的(但很好)的副作用是,如果没有返回数据,表就会清空,表明我们什么也没得到。