我正在将这个小JSON函数与数据库一起使用。
<script>
$(document).ready(function () {
var url = "Database.php";
$("#jsondata tbody").html("");
$.getJSON(url, function (data) {
$.each(data.users, function (i, user) {
var songdetails = "<p>"
+ "<p>" + user.Title + "</p>"
+ "<p>" + user.ArtistNumber + "</p>"
+ "<p>" + user.TrackTime + "</p>"
+ "<p>" + user.Composer + "</p>"
+ "<p>" + user.Lyricist + "</p>"
+ "</p>";
$(songdetails).appendTo("songlist");
});
});
});
</script>
这在浏览器中产生了这个,我不想要/不需要。
{ “用户”:[{ “标题”: “继续”, “ArtistNumber”: “2”, “TrackTime”: “167”, “作曲”:“约翰 釉 “ ”作词“:” Kellee 玉米”, “FileLocation”: “公共/ Anyway.mp3”, “额定”: “0”, “得分”: “[0,0,0,0,0]”, “免费”: “0”}, {“标题”:“一 Way Heartbeats“,”ArtistNumber“:”4“,”TrackTime“:”187“,”作曲家“:”比尔 鲍勃“‘作词’:”迈克尔· McEachern”, “FileLocation”: “公共/ OneWayHeartbeats.mp3”, “额定”: “0”, “得分”: “[0,0,0,0,0]”, “免费”: “0”}, {“标题”:“并行 我 “ ”ArtistNumber“: ”3“, ”TrackTime“: ”192“, ”作曲“:” 很 革命“‘作词’:”很 革命”, “FileLocation”: “私人/ ParallelMe.mp3”, “额定”: “0”, “得分”: “[0,0,0,0,0]”, “免费”: “1”}, {“标题”:“中毒 氧 “ ”ArtistNumber“: ”3“, ”TrackTime“: ”177“, ”作曲家“:” 很 革命“‘作词’:”很 革命”, “FileLocation”: “公共/ PoisonedOxygen.mp3”, “额定”: “0”, “得分”: “[0,0,0,0,0]”, “免费”: “0”}, {“标题”:“圣诞 “监狱蓝调”,“ArtistNumber”:“1”,“TrackTime”:“192”,“作曲家”:“史蒂夫 佩里“‘作词’:”史蒂夫 佩里”, “FileLocation”: “私人/ XmasPrisonBlues.wma”, “额定”: “0”, “得分”: “[0,0,0,0,0]”, “免费”: “1”}] }
有关如何隐藏或删除它的任何想法? 感谢
这是Database.php:
<?php
$Hostserver = "localhost";
$databUser = "ee2800";
$databPass = "secret";
$databDatabase = "ee2800";
$database = new mysqli ($Hostserver, $databUser, $databPass, $databDatabase);
if ($database) {
mysqli_select_db($database, "ee2800");
//echo ("Successfully connected to database!");
} else {
die ("<strong>Error:</strong> Failed to connect to the database.");
}
$var = array();
$sql = "SELECT * FROM songs";
$result = mysqli_query($database, $sql);
while ($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"users":' . json_encode($var) . '}';
?>
使用jQuery 1.10.2 歌曲列表元素可在此处找到
<?php
// The system queries the database to obtain a result set containing no more than 10 artists //
if ($result = $database->query( "SELECT * FROM `artist` ORDER BY `artist`.`ArtistNumber` ASC LIMIT 10")) {
while ($row = $result->fetch_row()) {
echo "<div id='artist{$row[2]}'>";
echo "<p>Artist: {$row[0]} {$row[1]}</p>";
echo '<p><a href="#Songs" id="song' . $row[2] . '"><div id= songlist> </div> </a></p>';
//div tag 'songlist' adds all data from json and pastes into this div id //
// echo '<p><a href="#" id="songlist' . $row[2] . '">Songs</a></p>';
//onlick function echo'd anchor tag//
echo "</div>";
// Songs dont display onclick however retrieved data using jSON can't seem to target where to put the information //
}
}
$database->close();
?>
基本上每当我运行这些文件时,我都会得到我在开头时所说的长字符串作为每次浏览器的响应。
答案 0 :(得分:0)
你的PHP似乎正在返回一个有效的json字符串,但它并没有被自动转换为json对象,所以它可以被javascript作为对象处理。
你可以尝试强制解析像这样的json对象
$.getJSON(url, function (data) {
data = $.parseJSON(data);
$.each(data.users, function (i, user) {