使用Ajax在表格中获取数据

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

Fetching data using ajax in a table

问题

<!DOCTYPE html>
<html>
  <head>
    <title>从API获取数据并使用AJAX在表格中显示</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <h1>数据</h1>
    <table id="table" border="1"></table>

    <script>
      function load(){
        fetch("url")
          .then(result => result.json())
          .then(json => show(json))
      }
      
      function show(data){
        let table = document.getElementById('table');
        for(let i=0; i< data.length; i++){
          let obj = data[i];
          console.log(obj);
          let row = document.createElement('tr');
          let name = document.createElement('td');
          name.innerHTML = obj.username;
          row.appendChild(name);
          let viewMoreButton = document.createElement('td');
          let button = document.createElement('button');
          button.innerHTML = "查看更多";
          button.addEventListener("click", function(){
            // 在这里添加从另一个API获取数据的代码
          });
          viewMoreButton.appendChild(button);
          row.appendChild(viewMoreButton);
          table.appendChild(row);
        }
      }
    </script>
  </body>
</html>

这是你提供的HTML代码的翻译,我还添加了一个"查看更多"按钮,并为该按钮添加了一个点击事件监听器,以便你可以在点击按钮时执行从另一个API获取数据的操作。

英文:
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Fetch data from API and display in table using AJAX&lt;/title&gt;
    &lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;Data&lt;/h1&gt;
    &lt;table id=&quot;table&quot; border=&quot;1&quot;&gt;&lt;/table&gt;

    &lt;script&gt;
      function load(){
        fetch(&quot;url&quot;)
          .then(result =&gt; result.json)
          .then(json =&gt; show(json)) }
      function show(data){
      let table = document.getElementById(&#39;table&#39;);
      for(let i=0; i&lt; data.length; i++){
        let obj = data[i];
        console.log(obj);
        let row = document.createElement(&#39;tr&#39;);
        let name = document. createElement(&#39;td&#39;);
        id.innerHTML = obj.
        row.appendChild(name)
        table.appendChild(row)
  }


}
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;

I need to fetch data from a url. I have to present it in a table. First I only need to display username with a button "view more". When view more will be clicked I have to fetch data from another api related to that particular username .I have written few line of code but they are not working. Any suggestionns? your text

答案1

得分: 1

it might be better to use $.append instead of appenChild

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

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




从API获取数据并使用AJAX在表格中显示


Data

<script>
  async function load(){
    let json = await(
    await fetch("https://gorest.co.in/public/v2/users")
    ).json()
    show(json) 
      }
  function show(data){
  for(let i=0; i< data.length; i++){
    let obj = data[i];
    $('#table tbody').append(`
      <tr>
        <td> ${obj.name} </td>
        <td> ${obj.email} </td>
      </tr>
    `)
   }
 };load()
</script>


<!-- end snippet -->

英文:

it might be better to use $.append instead of appenChild

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

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

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Fetch data from API and display in table using AJAX&lt;/title&gt;
    &lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;Data&lt;/h1&gt;
    &lt;table id=&quot;table&quot;&gt;
       &lt;tbody&gt;&lt;/tbody&gt;
    &lt;/table&gt;

    &lt;script&gt;
      async function load(){
        let json = await(
        await fetch(&quot;https://gorest.co.in/public/v2/users&quot;)
        ).json()
        show(json) 
          }
      function show(data){
      for(let i=0; i&lt; data.length; i++){
        let obj = data[i];
        $(&#39;#table tbody&#39;).append(`
          &lt;tr&gt;
            &lt;td&gt; ${obj.name} &lt;/td&gt;
            &lt;td&gt; ${obj.email} &lt;/td&gt;
          &lt;/tr&gt;
        `)
       }
     };load()
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

答案2

得分: 0

以下是翻译好的内容:

这里是一个更简单的纯JavaScript版本

你需要调用 .json() 来获取对象

我只是猜测你在 "显示更多" 方面的意思,但这里是一个可工作的脚本

let table;
const show = (data) => {
  table.innerHTML = data
    .map(({id,name,email, gender,status}) => `<tr>
      <td colspan="3">${name} <button class="more" data-id="${id}">查看更多...</button></td></tr>
      <tr hidden><td>${email}</td>
      <td>${gender}</td>
      <td>${status}</td>
      </tr>`)
    .join("");
};
const load = () => {
  fetch("https://gorest.co.in/public/v2/users")
    .then(result => result.json())
    .then(show);
};
window.addEventListener("DOMContentLoaded", () => {
  table = document.getElementById('table');
  table.addEventListener("click", (e) => {
    const tgt = e.target.closest("button");
    if (!tgt) return;
    // 如果需要,可以从 tgt.dataset.id 获取 id
    tgt.closest("tr").nextElementSibling.hidden = false;
  })
  load();
});
.more { float:right; margin-left: 5px; }
<h1>数据</h1>
<table border="1">
  <tbody id="table"></tbody>
</table>
英文:

Here is a simpler plain JavaScript version

You need to call .json() to get the object

I am only guessing what you meant with "show more" but here is a working script

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

<!-- language: lang-js -->

let table;
const show = (data) =&gt; {
  table.innerHTML = data
    .map(({id,name,email, gender,status}) =&gt; `&lt;tr&gt;
      &lt;td colspan=&quot;3&quot;&gt;${name} &lt;button class=&quot;more&quot; data-id=&quot;${id}&quot;&gt;view more...&lt;/button&gt;&lt;/td&gt;&lt;/tr&gt;
      &lt;tr hidden&gt;&lt;td&gt;${email}&lt;/td&gt;
      &lt;td&gt;${gender}&lt;/td&gt;
      &lt;td&gt;${status}&lt;/td&gt;
      &lt;/tr&gt;`)
    .join(&quot;&quot;);
};
const load = () =&gt; {
  fetch(&quot;https://gorest.co.in/public/v2/users&quot;)
    .then(result =&gt; result.json())
    .then(show);
};
window.addEventListener(&quot;DOMContentLoaded&quot;, () =&gt; {
  table = document.getElementById(&#39;table&#39;);
  table.addEventListener(&quot;click&quot;, (e) =&gt; {
    const tgt = e.target.closest(&quot;button&quot;);
    if (!tgt) return;
    // id can be gotten from tgt.dataset.id if needed
    tgt.closest(&quot;tr&quot;).nextElementSibling.hidden = false;
  })
  load();
});

<!-- language: lang-css -->

.more { float:right; margin-left: 5px; }

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

&lt;h1&gt;Data&lt;/h1&gt;
&lt;table border=&quot;1&quot;&gt;
  &lt;tbody id=&quot;table&quot;&gt;&lt;/tbody&gt;
&lt;/table&gt;

<!-- end snippet -->

答案3

得分: 0

管理view moreid数据以实现更多功能。这更加有效。

<!DOCTYPE html>
<html>
  <head>
    <title>从API获取数据并使用AJAX在表格中显示</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <h1>数据</h1>
    <table id="table" border="1">
      <tbody></tbody>
    </table>
    <script>
      let moreData = {}
      function viewMore(id){
        console.log(moreData[id])
      }
      function show(data){
        data.forEach(obj=>{
         moreData[obj.id] = obj;
        $('#table tbody').append(`
          <tr>
            <td> ${obj.name} </td>
            <td ><button onclick="viewMore(${obj.id})">
            查看更多</button></td>
          </tr>`)})
       }
    $(document).ready(function(){
      $.get("https://gorest.co.in/public/v2/users", show)
    })
    </script>
  </body>
</html>

请注意,代码部分未翻译。

英文:

manage view more with id data for more functionality. it is more effective
<!-- begin snippet: js hide: false console: true babel: false -->

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

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Fetch data from API and display in table using AJAX&lt;/title&gt;
    &lt;script src=&quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;Data&lt;/h1&gt;
    &lt;table id=&quot;table&quot; border=&quot;1&quot;&gt;
       &lt;tbody&gt;&lt;/tbody&gt;
    &lt;/table&gt;
    &lt;script&gt;
      let moreData = {}
      function viewMore(id){
        console.log(moreData[id])
      }
      function show(data){
        data.forEach(obj=&gt;{
         moreData[obj.id] = obj;
        $(&#39;#table tbody&#39;).append(`
          &lt;tr&gt;
            &lt;td&gt; ${obj.name} &lt;/td&gt;
            &lt;td &gt;&lt;button onclick=&quot;viewMore(${obj.id})&quot;&gt;
            View More&lt;/button&gt;&lt;/td&gt;
          &lt;/tr&gt;`)})
       }
    $(document).ready(function(){
      $.get(&quot;https://gorest.co.in/public/v2/users&quot;, show)
    })
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月11日 14:37:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224760.html
匿名

发表评论

匿名网友

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

确定