在HTML显示JSON [英] Display json in html
问题描述
大家好,我想在一个HTML文件从MySQL表中显示的数据。我有一个工作的PHP文件:
< HTML>
< HEAD>
< /头>
<身体GT;
< PHP
$库MySQLi =新库MySQLi(本地主机,用户,通,DB);
如果(mysqli_connect_errno()){
的printf(无法连接到SQL Server错误code%S \ñ,mysqli_connect_error($ mysqli的));
出口;
}
$名称= $ _ POST ['名称'];
//设置默认的命名空间为utf8
$ mysqli->查询(SET NAMES'UTF8');
$ JSON =阵列();
如果($结果= $ mysqli->查询(选择名称,设备,punkte从freefallhighscores ORDER BY punkte降序极限0,50)){
而($行= $ result-> FETCH_ASSOC()){
$ JSON [] =阵列(
'名'=> $行['名称'],
'设备'=> $行['设备'],
punkte'=> $行['punkte']
);
}
}
$ result->关闭();
标题(内容类型:text / JSON);
回声json_en code(阵列('结果'=> $ JSON));
$ mysqli->关闭();
?>
< /身体GT;
< / HTML>
当我运行PHP文件,我得到预期的回应:
<$p$p><$c$c>{"results":[{"name":"Benane","device":"iPhone4,1","punkte":"5000"},{"name":"Tillazh","device...等等。现在我想在一个HTML表格中显示此数据。要做到这一点,我要传递的数据(JSON变量)到HTML文件(也许用$ _ POST功能?)。我怎样才能做到这一点?难道是适当使用XMLHtt prequest(XHR)?
是的,除非你要使用这个模式很多次,即使这样,因为你已经导出从PHP数据库表,并且不使用多个目标格式,就没有必要使用JSON
最简单的解决办法是这样的:
&LT;表&gt;&LT; PHP
的foreach($ JSON作为$ K =&GT; $ V){
回声'&其中; TR&GT;&其中;第i个',$ K,'&所述; /第i;&其中; TD&GT;',$ V,'&所述; / TD&GT;&所述; / TR&GT;';
}
?&GT;&LT; /表&gt;
Hi guys, I would like to display data from a MySQL table in a HTML file. I have a working PHP file:
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost","user","pass","db");
if (mysqli_connect_errno()) {
printf("Can't connect to SQL Server. Error Code %s\n", mysqli_connect_error($mysqli));
exit;
}
$name = $_POST['name'];
// Set the default namespace to utf8
$mysqli->query("SET NAMES 'utf8'");
$json = array();
if($result = $mysqli->query("SELECT name, device, punkte FROM freefallhighscores ORDER BY punkte DESC LIMIT 0, 50")) {
while ($row=$result->fetch_assoc()) {
$json[]=array(
'name'=>$row['name'],
'device'=>$row['device'],
'punkte'=>$row['punkte']
);
}
}
$result->close();
header("Content-Type: text/json");
echo json_encode(array( 'results' => $json ));
$mysqli->close();
?>
</body>
</html>
When I run the PHP file, I get the expected echo:
{"results":[{"name":"Benane","device":"iPhone4,1","punkte":"5000"},{"name":"Tillazh","device... and so on.
Now I want to display this data in an HTML table. To do so, I have to pass the data (JSON variable) to an HTML file (maybe using the $_POST function?). How can I do this? Would it be appropriate to use an XMLHttpRequest (XHR)?
Yes, unless you are going to use this pattern a lot of times, and even then, since you're already exporting the database table from PHP and are not using multiple target formats, there is no need to use JSON.
The simplest solution would be something like:
<table><?php
foreach ($json as $k=>$v){
echo'<tr><th>',$k,'</th><td>',$v,'</td></tr>';
}
?></table>
这篇关于在HTML显示JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!