2017-05-30 57 views
-3

是否可以显示来自json的数据html? 我有例子,但它只是表。是否有可能存储数据json到html(不是表格)

<table id="tables" 
data-url="comments.php" 
data-row-style="rowStyle" 
data-toggle="table" 
data-show-refresh="true" 
data-show-toggle="true" 
data-show-columns="true" 
data-search="true" 
data-select-item-name="toolbar1" 
data-pagination="true" 
data-sort-name="name" 
data-sort-order="desc"> 
<thead> 
<tr> 
<th data-field="name" data-sortable="true" data-align="left">Name</th> 
<th data-field="comments" data-sortable="true" data-align="left">comments</th> 
</tr> 
</thead> 
<tr> 
</tr> 
</table> 

我要显示/加载数据从JSON来HTML:

<h3>name</h3>//data from json 
<p>comments</p>//data from json 

的comments.php

<?php 
header('content-type:application/json'); 
include 'connection.php'; 

$select = mysql_query("select * from comments"); 
$row=array(); 

while($row=mysql_fetch_array($select)) 
{ 
    $arrayx=array( "comments"=>$row['comments'], 
        "name"=>$row['name']); 

    $rows[] = $arrayx; 

} 
echo json_encode($rows); 
?> 

我有例如JSON像..

+0

是的,使用AJAX。 –

+0

*“我有示例,但它仅用于表格”* - 您的示例仅为HTML,它根本没有与JSON的连接。您将使用什么相应的JS来从JSON填充该表格? – nnnnnn

+0

我已添加jsonComments.php –

回答

0

它可以按照你的要求,你的HTML内联。

但使用jQuery .get(),这是可以做到这样:

HTML:

<h3 id="jsonName"></h3><!--data from json will be here --> 
<p id="jsonComments"></p><!--data from json will be here --> 

jQuery脚本:

$.get("comments.php","",function(data){ 
    $("#jsonName").html(data.name); 
    $("#jsonComments").html(data.comments); 

    //To look at the received json 
    console.log(JSON.stringify(data)); 
},"json"); 

如果你的JSON有很多物体使用类而不是ids。
并循环访问数据。

+0

不工作先生。 json需要编码吗? –

+0

我认为'comments.php'返回一个有效的json。 –

+0

我编辑过...尝试它并发布您在控制台中看到的内容。 –

相关问题