如何使用JavaScript将JSON显示到html表中?

如何使用JavaScript将JSON显示到html表中?,javascript,html,html-table,Javascript,Html,Html Table,我有一段javascript代码,旨在将数据显示到我的html表中。我现在一直在思考如何将数据显示到html中。以下是我的代码片段: document.getElementById('save-book').addEventListener('click', (e) =>{ books = ''; if(document.getElementById('books').value){ books = document.getElementById('book

我有一段javascript代码,旨在将数据显示到我的html表中。我现在一直在思考如何将数据显示到html中。以下是我的代码片段:

document.getElementById('save-book').addEventListener('click', (e) =>{
    books = '';
    if(document.getElementById('books').value){
        books = document.getElementById('books').value;
    }

    book_name = document.getElementById('book_name').value;
    description = document.getElementById('description').value;

    if(book_name && description){
        books = books.replace("[","").replace("]","");
        let book_object = {"id": 0, "book_name": book_name, "description": description};
        book_object = JSON.stringify(book_object);

        books = "["+books+", "+book_object+"]";

        for (var i = JSON.parse(books).length - 1; i >= 0; i--) {
            console.log(JSON.parse(books)[i].id);
            //replace the current rows from a table by this object books.
        }

    }

    document.getElementById('book_name').value = '';
    document.getElementById('description').value = '';
});
其中我的
books
标记保存的数据

[{"id": 1, "book_name":"Harry Potter","description":"Harry Potter is a series of fantasy novels written by British author J. K. Rowling"},{"id" : 2, "book_name":"Wizard of Oz","description":"The description here"}]
我的桌子是这样的:

<table id="book_table" class="display">
    <thead>
        <tr>
            <th class="hide">Id</th>
            <th>Book Name</th>
            <th>Description</th>
            <th class="right-align">Action</th>
        </tr>
    </thead>
    <tbody>
        @if($books->count() > 0)
        @foreach ($books as $book)
        <tr>
            <td class="hide">{{ $book->id }}</td>
            <td>{{ $book->book_name }}</td>
            <td>{{ $book->description }}</td>
            <td></td>
        </tr>
        @endforeach 
        @endif
    </tbody>
</table>

身份证件
书名
描述
行动
@如果($books->count()>0)
@foreach($books作为$book)
{{$book->id}
{{$book->book_name}
{{$book->description}
@endforeach
@恩迪夫

如何将我的books数组替换并显示到上表中?

这就是您要做的吗

//您的演示数据
var账簿=[
{“id”:1,“书名”:“哈利·波特”,“描述”:“哈利·波特是英国作家J.K.罗琳写的一系列幻想小说”},
{“id”:2,“书名”:“绿野仙踪”,“描述”:“这里的描述”}
];
//这将是保存数据的地方
var booksTable=document.querySelector(“#book_table tbody”);
//翻阅记录
对于(var i=0;i
表格{宽度:100%}

身份证件
书名
描述
行动

那些
@foreach
$book->id
等注释是什么?这是我的php刀片符号。但是我想在用户创建一个新的数据并将其保存到数据库之前立即替换该数据。使用XMLhttprequest并解析数据或使用JavaScript获取。这是否回答了您的问题@好的,XMLhttpRequest是从页面到数据库的吗?