我正在练习使用JSON,但似乎没有检索到预期的信息。如何使用JSON从MySQL中检索信息?
该页面直接在HTML输出中显示来自数据库的用户详细信息,使用JSON。
的getJSON
</p>
<?php
$mysql_db_hostname = "host";
$mysql_db_user = "user";
$mysql_db_password = "pass";
$mysql_db_database = "db";
$con = @mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,
$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$var = array();
$sql = "SELECT * FROM users";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"users":'.json_encode($var).'}';
?>
<p style="text-align: justify;">
和showjson
</p>
<table class="mGrid" id="jsondata">
<thead>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Location</th>
</thead>
<tbody></tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function(){
var url="getjson.php";
$("#jsondata tbody").html("");
$.getJSON(url,function(data){
$.each(data.users, function(i,user){
var newRow =
"<tr>"
+"<td>"+user.id+"</td>"
+"<td>"+user.name+"</td>"
+"<td>"+user.age+"</td>"
+"<td>"+user.gender+"</td>"
+"<td>"+user.location+"</td>"
+"</tr>" ;
$(newRow).appendTo("#jsondata tbody");
});
});
});
</script>
<p style="text-align: justify;">
数据库用户ID,姓名,性别,位置
你能提供一些输出吗?什么是期望值,什么是收到价值? – 2014-08-31 09:17:55
其没有获取数据 – mukesh 2014-08-31 09:29:49
看看你的浏览器的开发者工具。重新加载页面。 JavaScript控制台说什么?你能在Net标签中看到你的Ajax请求吗?它格式正确吗?它会得到回应吗?答案是否正确? – Quentin 2014-08-31 09:31:49