我有一个显示图像的书签页面。图像正好在图像上方显示,从中检索图像的阵列也显示如下:
[[" 1"," img / exampleImage1.png"],[" 2"," img / exampleImage2.png" ]
这是书签页面
<?php include 'retrieveSymbol.php';?>
<div id="bookmarkedSymbols"></div>
<script>
//populates product container
$.getJSON("retrieveSymbol.php", function(data){ //retrieves json array
$.each(data, function(i, field){ //loops through array
$("#bookmarkedSymbols").append(
//creates product box filling it with data
"<img src='" + field[1] + "'" + "id='symbol' alt='stadium'></a>"
);
});
});
</script>
这是检索符号页面:
<?php
//connect to the database
$mysqli = NEW MySQLi ('localhost','root','','bookmarkedSymbols');
//query database
$resultSet = $mysqli->query("SELECT * FROM symbols");
//count the rows
if($resultSet->num_rows != 0) {
//turn the results into an array
$rows = $resultSet->fetch_all();
echo json_encode($rows);
}else{
echo "{no connection}";
}
?>
答案 0 :(得分:3)
在带有JS的页面中,您不需要包含retrieveSymbol.php
,因为您使用AJAX调用它。
删除它:
<?php include 'retrieveSymbol.php';?>
当你包含php脚本时,它会直接在页面上回显JSON。
答案 1 :(得分:1)
避免在同一PHP文件中再次显式包含PHP脚本。因为这将通过JavaScript异步触发!
尝试如下。
<div id="bookmarkedSymbols"></div>
<script type="text/javascript">
//populates product container
$.getJSON("retrieveSymbol.php", function(data){ //retrieves json array
$.each(data, function(i, field){ //loops through array
$("#bookmarkedSymbols").append(
//creates product box filling it with data
"<img src='" + field[1] + "'" + "id='symbol' alt='stadium'></a>"
);
});
});
</script>
您可以为此代码添加document.ready函数,如下所示。
$( document ).ready(function() {
console.log( "ready!" );
});
或者如下所示。
$(function() {
console.log( "ready!" );
});
您的retrieveSymbol.php
代码案例包含无效的json并添加JSON Content Header
,如下所示。
<?php
//connect to the database
$mysqli = NEW MySQLi ('localhost','root','','bookmarkedSymbols');
//query database
$resultSet = $mysqli->query("SELECT * FROM symbols");
//count the rows
header('Content-Type: application/json');
if($resultSet->num_rows != 0) {
//turn the results into an array
$rows = $resultSet->fetch_all();
echo json_encode($rows);
}else{
echo '{"msg": "no connection"}';
}
?>