【问题标题】:Display json in html在html中显示json
【发布时间】:2013-08-19 10:22:03
【问题描述】:

大家好,我想在 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 html mysql ajax json


【解决方案1】:

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

最简单的解决方案是这样的:

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

【讨论】:

  • 同意,简单胜过复杂。除非您的应用程序已经使用 JSON,否则不要使用 JSON。如果它只是一个服务器端的 PHP 应用程序,那么不要为中间格式而烦恼。
【解决方案2】:

我的代码中的简单 php 函数:

function json_object_to_html($json_object_string){

           $json_object=json_decode($json_object_string);
           if(!is_object($json_object)) {
               if (is_array($json_object)){
                   $result="[ <br>";
                   foreach($json_object as $json_obj){
                       $result.="<div style='margin-left:30px'>".json_object_to_html( json_encode( $json_obj ) )."</div>";

                       if(end($json_object)!=$json_obj)
                           $result.=",";
                   }
                   return $result."  ] <br>";
               }
               else
                   return json_decode($json_object_string);

           }

           $result = "";

           foreach($json_object as $key => $value){
               $str_value=json_object_to_html( json_encode($value) );
               $result.="<span><span style='font-weight: bold'>$key : </span>$str_value</span><br>";
           }

           return $result;

        }

【讨论】:

    猜你喜欢
    • 2016-11-09
    • 2017-02-03
    • 1970-01-01
    • 2013-12-22
    • 2011-05-25
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多