我有一个显示图像的书签页面。图像显示正常,但是在图像上方,还显示从中检索图像的数组,例如:
[["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}";
}
?>
在带有 JS 的页面中,您不需要包含retrieveSymbol.php
,因为您正在使用 AJAX 调用它。
删除此内容:
<?php include 'retrieveSymbol.php';?>
当您包含 php 脚本时,它会直接在页面上回显 JSON。
避免在同一 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
代码 else 情况具有无效的 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"}';
}
?>