我正在尝试使用jQuery的$ .getJSON函数从PHP获取JSON来填充表格。在PHP方面,我使用echo json_encode。它可以正常工作,表格被填满,但数组的表示形式也可以在站点顶部看到,如下所示:
“ [{{id”:“ 1”,“ 0”:“ 1”,“ author”:“ Tolkien”,“ 1”:“ Tolkien”,“ title”:“ Gyuruk Ura”,“ 2” :“ Gyuruk Ura”,“ isbn”:“ 8759”,“ 3”:“ 8759”},{“ id”:“ 2”,“ 0”:“ 2”,“ author”:“ Tolkien”,“ 1 “:” Tolkien“,” title“:” Hobbit“,” 2“:” Hobbit“,” isbn“:” 8759“,” 3“:” 8759“}]”
jQuery代码:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
let books = "";
$.getJSON( "ViewBookstore.php", function( data ) {
$.each( data, function( index, value ) {
books += "<tr>";
books += "<td>"+value.author+"</td>";
books += "<td>"+value.title+"</td>";
books += "<td>"+value.isbn+"</td>";
books += '<td>' +
'<button class="btn btn-info" id="edit">Edit</button>' +
'<button class="btn btn-danger" id="delete">Delete</button>' +
'</td>';
books += "</tr>";
});
$("#books-table").append(books);
});
});
</script>
我的PHP代码:
class ViewBookstore extends ControllerBookstore
{
public function showAllBooks(){
echo json_encode($this->getAllBooks());
}
}
$view = new ViewBookstore();
$view->showAllBooks();
答案 0 :(得分:0)
您的jquery代码在ViewBookstore.php中?因此您的php代码正在运行,并在页面顶部显示该结果。为防止出现一些控制语句,例如:
这是一个非常简单的示例
更改
$.getJSON( "ViewBookstore.php", function( data ) {
到
$.getJSON( "ViewBookstore.php?show_books=true", function( data ) {
并在ViewBookstore.php中进行更改
$view = new ViewBookstore();
$view->showAllBooks();
使用
if(!empty($_GET['show_books']))
{
$view = new ViewBookstore();
$view->showAllBooks();
}