在javascript中插入数据到新行

j7dteeu8  于 2023-03-11  发布在  Java
关注(0)|答案(1)|浏览(92)

我们从服装(mocki.io和假json)url中使用XMLHttpRequest获取数据,我想在新标签中插入名称和城市!但是在此代码中,将所有数据element.name和element.city设置在一个表行中!!我们应该有4个,并且在每个tr标签中,我们应该有两个td标签,包括名称和城市数据。
可以帮我在新表格行中设置对(姓名,城市)吗?
谢谢。

<html lang="en">
        <head>
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>AJAX</title>
        </head>
        <body>
            <h1 style="text-align:center" id="data"></h1>
            <table id="table" class="table">
                <thead>
                    <tr>
                        <th>name</th>
                        <th>city</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td id="name"></td>
                        <td id="city"></td>
                    </tr>
                </tbody>
            </table>
        <script>
    
            // Create XML HTTP Request
            let xHTTP = new XMLHttpRequest();
            xHTTP.open('GET','https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8');
            xHTTP.onload = () => {
                if (xHTTP.status == 200 && xHTTP.readyState == 4){
                }
            }
            
            // Separeted Object Data
            function processResult(result){
                result.forEach(element => {
                    console.log(element);
                    console.log(element.name);
                    document.getElementById('name').innerHTML  +=  element.name + '</br>';
                    document.getElementById('city').innerHTML  +=  element.city + '</br>';
                });
            }
    
            // GET DATA from URL
            let response;
            xHTTP.onreadystatechange = function(){
                if (xHTTP.status == 200 && this.readyState == 4){
                    console.log('AJAX was succeed');
                    response = JSON.parse(this.response);
                    console.log('my response is: ',response);
                    console.log(typeof(response));
                    processResult(response); 
                }
            };
    
            // SEND Result to server
            xHTTP.send();
        </script>
    </body>
    </html>

<!-- begin snippet: js hide: false console: true babel: false -->
nlejzf6q

nlejzf6q1#

老实说,按照你解释的方式,很难理解你的问题。
我所能理解的是,您正在尝试在创建的表中正确显示获取的数据。

您的问题:

您正面临一个问题,因为您以纯文本形式更改<td> (table data)的innerHTML,而没有将其 Package 在新的<tr> (table row)中。
更准确地说:您需要为每个结果(电影和名称)创建一个新的表行,以正确显示表。现在您将所有结果放在一个<tr>中,其中包含两个<td>。要匹配您的结果,您需要在其中包含4 <tr> with 2 <td>

**可能的解决方案1:***速度快且受所有浏览器版本支持 *

确保表格正确显示的更简单方法(对于旧版本的浏览器也是如此)是直接访问<tbody>,并将新的<tr>, <td> and your data附加到<tbody>.innerHTML中,如下所示:

<html lang="en">
  <head>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
      integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
      crossorigin="anonymous"
    />
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AJAX</title>
  </head>
  <body>
    <h1 style="text-align: center" id="data"></h1>
    <table id="table" class="table">
      <thead>
        <tr>
          <th>Name</th>
          <th>City</th>
        </tr>
      </thead>
      <tbody id="tableData"></tbody>
    </table>
    <script>
      // Create XML HTTP Request
      let xHTTP = new XMLHttpRequest();
      xHTTP.open(
        "GET",
        "https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8"
      );
      xHTTP.onload = () => {
        if (xHTTP.status == 200 && xHTTP.readyState == 4) {
        }
      };

      // Separeted Object Data
      function processResult(result) {
        result.forEach((element, i) => {
          document.getElementById(
            "tableData"
          ).innerHTML += `<tr id="result${i}"><td id=MovieName${i}>${element.name}</td><td id=CityName${i}>${element.city}</td></tr>`;
        });
      }

      // GET DATA from URL
      let response;
      xHTTP.onreadystatechange = function () {
        if (xHTTP.status == 200 && this.readyState == 4) {
          response = JSON.parse(this.response);
          processResult(response);
        }
      };

      // SEND Result to server
      xHTTP.send();
    </script>
  </body>
</html>

<!-- begin snippet: js hide: false console: true babel: false -->

**可能的解决方案2:**此解决方案有效,但速度慢得多。

您可以尝试为从请求中获得的每个结果创建一个新的表行.createElement(),添加两个新的TextNode(使用.createTextNode),然后将数据“movie”和“city”(使用.appendChild())添加到新创建的表行中的two different <td>
如果你这样做,它可能看起来像这样:

<html lang="en">
  <head>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
      integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
      crossorigin="anonymous"
    />
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AJAX</title>
  </head>
  <body>
    <h1 style="text-align: center" id="data"></h1>
    <table id="table" class="table">
      <thead>
        <tr>
          <th>Name</th>
          <th>City</th>
        </tr>
      </thead>
      <tbody id="tableData"></tbody>
    </table>
    <script>
      // Create XML HTTP Request
      let xHTTP = new XMLHttpRequest();
      xHTTP.open(
        "GET",
        "https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8"
      );
      xHTTP.onload = () => {
        if (xHTTP.status == 200 && xHTTP.readyState == 4) {
        }
      };

      // Separeted Object Data
      function processResult(result) {
        result.forEach((element) => {
          const tableRowNode = document.createElement("tr");
          const tableNodeMovie = document.createElement("td");
          const tableNodeCity = document.createElement("td");
          const movieTextNode = document.createTextNode(element.name);
          const cityTextNode = document.createTextNode(element.city);
          tableNodeMovie.appendChild(movieTextNode);
          tableNodeCity.appendChild(cityTextNode);
          tableRowNode.appendChild(tableNodeMovie);
          tableRowNode.appendChild(tableNodeCity);
          document.getElementById("tableData").appendChild(tableRowNode);
        });
      }

      // GET DATA from URL
      let response;
      xHTTP.onreadystatechange = function () {
        if (xHTTP.status == 200 && this.readyState == 4) {
          response = JSON.parse(this.response);
          processResult(response);
        }
      };

      // SEND Result to server
      xHTTP.send();
    </script>
  </body>
</html>

相关问题