抱歉,如果重复的话,但是我已经研究过了,在这里找不到任何帮助。我有一些来自学校的旧作业代码,该代码将数据收集到JSON数组中并将其输出到创建图像网格的div
中。我正在尝试重用它,但是我被卡住了。
我已经连接到数据库,并且正在将JSON打印到php文件中,但是我无法正确获取语法以使其在所需的php页面上打印数组。
我所拥有的:
section
的id
为board_table
scripts/surfboard.js
内的一个JS块,试图将JSON数据.append
到board_table
scripts/surfboard.js
包含在包含的head.php
文件我想要的:
surfboards.php
中的JSON将动态输出到equipment.php
,并附加到board_table
,使用surfboard.js
中的代码:
//gets the JSON from our surfboards.php
$.getJSON("surfboards.php", function (data) {
//loop through each surfboard in the JSON file and append id="board_table" with the surfboard information
$.each(data.Surfboards, function (row) {
$("#board_table").append(
'<div class="surfboard"><a href="equipment.php?id=' + data.Surfboard[row].Surfboard.id + '"><img src="images/' + data.Surfboard[row].Surfboard.imageName + '" alt="' + data.Surfboard[row].Surfboard.imageName + '"><p>' + data.Surfboard[row].Surfboard.name + '</p><p>$' + data.Surfboard[row].Surfboard.price + '</p></a></div>');
});
});
中的
surfboard.js
代码:<div class="flexbox_container">
<section id="board_table">
<h1><--Boards Should Show Here --></h1>
<!--/* Javascript will publish our products here */-->
</section>
</div>
来自
equpiment.php
的示例JSON块:{
"Surfboards": [
{
"Surfboard":
{
"id": "1",
"sNumber": "6",
"boardName": "Pat Curren Balsa Gun 12'",
"imageName": "camera.png",
"year": "1950",
"weight": "32",
"dimensions": "21",
"caDescription": "This board was built in Hawaii by Pat Curren, for Bev Morgan (early California wetsuit inventor and diving pioneer)",
"infoCard": "placeholder_infoCard",
"notes": ""
}
},
surfboards.php
文件中的代码: <!-- Start Scripts -->
<script src="jquery/dist/jquery.js"></script>
<script src="scripts/bootstrap.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script src="scripts/jquery.fullPage.min.js"></script>
<script src="scripts/modernizr.js"></script>
<script src="scripts/main.js"></script>
<script src="scripts/surfboard.js"></script>
任何帮助是极大的赞赏!
最佳答案
为了在本地测试,我模拟了您的surfboards.php并只是打印出了您提供的json(因为我没有您的数据库)
对我来说,好像您的json结构与surfboard.js
中的输出不对应
$.each(data.Surfboards, function (row) {
$("#board_table").append(
'<div class="surfboard"><a href="equipment.php?id=' + data.Surfboard[row].Surfboard.id + '">...</a></div>'
);
});
data.Surfboard
不可用-因为您的json以Surfboard 的开头。为了更容易,我会用
$.each(data.Surfboards, function (row, element) {
$("#board_table").append(
'<div class="surfboard"><a href="equipment.php?id=' + element.Surfboard.id + '"><img src="images/' + element.Surfboard.imageName + '" alt="' + element.Surfboard.imageName + '"><p>' + element.Surfboard.name + '</p><p>$' + element.Surfboard.price + '</p></a></div>'
);
});
使用该代码,我将显示在#board_table中的项目
第二件事-在您的github存储库中,您仍然使用$(“#board_table”)。append 附加到-但我认为您已经发现了这个问题:)