在 JavaScript 中插入数据到新行:

huangapple go评论89阅读模式
英文:

insert data in new row in javascript

问题

以下是您要翻译的内容:

we get data with XMLHttpRequest from costume( mocki.io and fake json) url, I want to insert name and city in new <tr> tag! but in this code set all data element.name and element.city in one table row!!
we should have 4 <tr></tr> and in every tr tag we should have two td tags include name and city data.

can help me to set pair (name, city) in new table row?

thanks.

翻译成中文如下:

我们使用XMLHttpRequest从自定义(mocki.io和虚假JSON) URL获取数据,我想将姓名和城市插入到新的<tr>标签中!但在此代码中,将所有数据element.name和element.city都设置在一个表行中!!
我们应该有4个<tr></tr>,每个tr标签中应包含两个td标签,包括姓名和城市数据。

可以帮助我将姓名和城市成对设置在新的表行中吗?

谢谢。

希望这可以满足您的需求。

英文:

we get data with XMLHttpRequest from costume( mocki.io and fake json) url, I want to insert name and city in new <tr> tag! but in this code set all data element.name and element.city in one table row!!
we should have 4 <tr></tr> and in every tr tag we should have two td tags include name and city data.

can help me to set pair (name, city) in new table row?

thanks.

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

<!-- language: lang-html -->

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

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

<!-- language: lang-html -->

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

<!-- end snippet -->

<!-- end snippet -->

答案1

得分: 1

以下是代码部分的翻译:

Possible solution 1: 快速且适用于所有浏览器版本

确保您的表格正确显示的更简单方法(也适用于较旧的浏览器版本)是直接访问您的 <tbody> 并将新的 <tr>、<td>和数据 添加到 <tbody>.innerHTML 中,如下所示:

<!DOCTYPE html>
<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>
      // 创建 XML HTTP 请求
      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) {
        }
      };

      // 分离的对象数据
      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>`;
        });
      }

      // 从 URL 获取数据
      let response;
      xHTTP.onreadystatechange = function () {
        if (xHTTP.status == 200 && this.readyState == 4) {
          response = JSON.parse(this.response);
          processResult(response);
        }
      };

      // 将结果发送到服务器
      xHTTP.send();
    </script>
  </body>
</html>

Possible solution 2: 这种解决方案有效,但速度较慢

您可以尝试为每个从请求中获得的结果创建一个新的表格行,附加两个新的 TextNodes(使用 .createTextNode),然后将数据(使用 .appendChild())"movie" 和 "city" 添加到新创建的表格行的两个不同的 <td> 中。之后,很容易将整个 <tr> 添加到实际表格以正确显示数据,如下所示:

<!DOCTYPE html>
<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>
      // 创建 XML HTTP 请求
      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) {
        }
      };

      // 分离的对象数据
      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);
        });
      }

      // 从 URL 获取数据
      let response;
      xHTTP.onreadystatechange = function () {
        if (xHTTP.status == 200 && this.readyState == 4) {
          response = JSON.parse(this.response);
          processResult(response);
        }
      };

      // 将结果发送到服务器
      xHTTP.send();
    </script>
  </body>
</html>

希望这些翻译对您有帮助。

英文:

To be honest it was quite difficult to understand your question as the way you explained it.

What i could understand is, that you are trying to display your fetched data correctly in your created table.

Your Problem:

You are facing a problem because you are changing the innerHTML of your &lt;td&gt; (table data) in plain text without wrapping it within a new &lt;tr&gt; (table row).

To be more precise: You would need a new table row for every result (movie and name) to display the table correctly. Right now you are placing all of your result in just one &lt;tr&gt;with two &lt;td&gt; inside. To match your results you would need 4 &lt;tr&gt; with 2 &lt;td&gt; inside.

Possible solution 1: Fast and supported by all Browser Versions

The much easier way of ensuring that your table is displayed correctly (also for older Browser Versions), is to access your &lt;tbody&gt; directly and appending the new &lt;tr&gt;, &lt;td&gt; and your data within the .innerHTML of your &lt;tbody&gt; like this:

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

<!-- language: lang-html -->

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

<!-- end snippet -->

Possible solution 2:
This solution works, but is much slower.

You could try to create a new table row with .createElement() for every result that you get from your request, append two new TextNodes (with .createTextNode) and then append your data (with .appendChild()) "movie" and "city" to two different &lt;td&gt; within the new created table row. Afterwards its quite easy to append the whole &lt;tr&gt; to your actual table to display the data correctly.

If you would do it this way it could look something like this:

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

<!-- language: lang-html -->

&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;link
rel=&quot;stylesheet&quot;
href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css&quot;
integrity=&quot;sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65&quot;
crossorigin=&quot;anonymous&quot;
/&gt;
&lt;meta charset=&quot;UTF-8&quot; /&gt;
&lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
&lt;title&gt;AJAX&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1 style=&quot;text-align: center&quot; id=&quot;data&quot;&gt;&lt;/h1&gt;
&lt;table id=&quot;table&quot; class=&quot;table&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;th&gt;City&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody id=&quot;tableData&quot;&gt;&lt;/tbody&gt;
&lt;/table&gt;
&lt;script&gt;
// Create XML HTTP Request
let xHTTP = new XMLHttpRequest();
xHTTP.open(
&quot;GET&quot;,
&quot;https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8&quot;
);
xHTTP.onload = () =&gt; {
if (xHTTP.status == 200 &amp;&amp; xHTTP.readyState == 4) {
}
};
// Separeted Object Data
function processResult(result) {
result.forEach((element) =&gt; {
const tableRowNode = document.createElement(&quot;tr&quot;);
const tableNodeMovie = document.createElement(&quot;td&quot;);
const tableNodeCity = document.createElement(&quot;td&quot;);
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(&quot;tableData&quot;).appendChild(tableRowNode);
});
}
// GET DATA from URL
let response;
xHTTP.onreadystatechange = function () {
if (xHTTP.status == 200 &amp;&amp; this.readyState == 4) {
response = JSON.parse(this.response);
processResult(response);
}
};
// SEND Result to server
xHTTP.send();
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月10日 00:34:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定