首页 > 解决方案 > 如何用 JS 将 HTML 重写为 HTML?

问题描述

我在应用程序切换到 REST/AJAX 之前拥有的这段 html 代码:

<div class="container">
<h2 align="center">TEACHERS</h2>
<table class="table table-dark" border="1" width="100%" cellpadding="5">
    <thead>
    <tr>
        <th> ID</th>
        <th> Name</th>
        <th> Position</th>

    </tr>
    </thead>
    <tbody>
    <tr th:if="${teachers.empty}">
        <td colspan="2"> No teachers Available</td>
    </tr>
    <tr th:each="teacher : ${teachers}">
        <td><a th:href="@{/teacherViews/teacherDescription(teacherId=${teacher.teacherId})}"><span
                th:text="${teacher.teacherId}"></span></a></td>
        <td><span th:text="${teacher.teacherName}"></span></td>
        <td><span th:text="${teacher.position}"></span></td>
    </tr>
    </tbody>
</table>

所以,在这里我有表格Teachers,当我点击- 1,2 或 10 时,我会在我点击的页面上teacherId抛出。teacherViews/teacherDescriptionteacherId

所以,我需要做同样的事情,但现在我使用 REST/AJAX。

现在我有 html :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="/teachers.js"></script>
<table id="table-content" class="table table-dark" border="1" width="100%" cellpadding="5">
<tr>
    <th>Teacher ID</th>
    <th>Teacher Name</th>
    <th>Teacher Position</th>
</tr>

teachers.js

var service = 'http://localhost:8081/';
$(document).ready(function(){

 jQuery.support.cors = true;

$.ajax(
    {
        type: "GET",
        url: service + 'check/',
         // data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
  var trHTML = '';

            $.each(data, function (i, teacher) {


                trHTML += '<tr><td>' + teacher.teacherId + '</td><td>' + teacher.teacherName + '</td><td>' + teacher.position + '</td></tr>';
            });

            $('#table-content').append(trHTML);
        },
  error: function (msg) {

            alert(msg.responseText);
        }
    });
})

此代码工作正常,表格显示在页面上。

据我了解,我需要 trHTML += '<tr><td>' + teacher.teacherId + '</td><td>' + teacher.teacherName + '</td><td>' + teacher.position + '</td></tr>'; });teachers.js.

标签: javascripthtml

解决方案


推荐阅读