在html中显示json

卢克

嗨,大家好,我想在HTML文件中显示MySQL表中的数据。我有一个正常工作的PHP文件:

<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>

当我运行PHP文件时,得到了预期的回显:

{"results":[{"name":"Benane","device":"iPhone4,1","punkte":"5000"},{"name":"Tillazh","device... and so on.

现在,我想在HTML表中显示此数据。为此,我必须将数据(JSON变量)传递到HTML文件(也许使用$ _POST函数?)。我怎样才能做到这一点?使用XMLHttpRequest(XHR)是否合适?

埃尔戈阿

是的,除非您要多次使用此模式,否则即使那样,由于您已经从PHP导出数据库表并且没有使用多种目标格式,因此无需使用JSON。

最简单的解决方案是:

<table><?php
foreach ($json as $k=>$v){
  echo'<tr><th>',$k,'</th><td>',$v,'</td></tr>';
}
?></table>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章