英文:
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获取数据的操作。
英文:
<!DOCTYPE html>
<html>
  <head>
    <title>Fetch data from API and display in table using AJAX</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <h1>Data</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');
        id.innerHTML = obj.
        row.appendChild(name)
        table.appendChild(row)
  }
}
    </script>
  </body>
</html>
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 -->
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 -->
<!DOCTYPE html>
<html>
  <head>
    <title>Fetch data from API and display in table using AJAX</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <h1>Data</h1>
    <table id="table">
       <tbody></tbody>
    </table>
    <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>
  </body>
</html>
<!-- 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) => {
  table.innerHTML = data
    .map(({id,name,email, gender,status}) => `<tr>
      <td colspan="3">${name} <button class="more" data-id="${id}">view more...</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;
    // id can be gotten from tgt.dataset.id if needed
    tgt.closest("tr").nextElementSibling.hidden = false;
  })
  load();
});
<!-- language: lang-css -->
.more { float:right; margin-left: 5px; }
<!-- language: lang-html -->
<h1>Data</h1>
<table border="1">
  <tbody id="table"></tbody>
</table>
<!-- end snippet -->
答案3
得分: 0
管理view more与id数据以实现更多功能。这更加有效。
<!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 -->
<!DOCTYPE html>
<html>
  <head>
    <title>Fetch data from API and display in table using AJAX</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <h1>Data</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})">
            View More</button></td>
          </tr>`)})
       }
    $(document).ready(function(){
      $.get("https://gorest.co.in/public/v2/users", show)
    })
    </script>
  </body>
</html>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论