如何将AJAX检索到的JSON格式的字符串转换为格式化的表格

I am new to web programming and have been having a lot of trouble with using AJAX to parse as a string and create a table.

[{"source":"1","name":"random","amount":"5"},{"source":"1","name":"random","amount":"5"}]

This is how the data is parsed as I used the code from W3SCHOOLS but adapted it to my situation I used the JSON stringify command to change it to a string also. https://www.w3schools.com/js/js_json_php.asp Based on the data above which has been retrieved by a AJAX code I am having troubles creating a table based on those results.

If you want your myObj in a format like table, then there is nothing that automatically converts from an object to table format built into html/javascript.

You could use some lib's to do this, but for something simple the below might be a start for you.

const myObj = [{"source":"1","name":"random","amount":"5"},{"source":"1","name":"random","amount":"5"}];

const tbody = document.querySelector("tbody");

myObj.forEach(r => {
  const tr = document.createElement("tr"); 
  ["source", "name", "amount"].forEach(f => {
    const td = document.createElement("td");
    td.innerText = r[f];
    tr.appendChild(td);
  });
  tbody.appendChild(tr);
});
<table border="1">
  <thead>
    <th>Source</th>
    <th>Name</th>
    <th>Amount</th>
  </thead>
  <tbody>
  </tbody>
</table>

</div>

You may want to consider some front end libraries to generate table like jquery DataTables or write your own implementation in pure JavaScript if you need something simpler.

The problem is that JSON.stringify does not create a table. It creates a json string of an object. you need to create a table yourself by appending tr elements to a table or tbody tag like so:

const json = JSON.parse('[{"source":"1","name":"random","amount":"5"},{"source":"1","name":"random","amount":"5"}]');

// querySelector is used to find an html element
// '#' means to search for an id so
// '#myTable' means to search to an element with the id 'myTable'
const tbody = document.querySelector('#myTable');

for (let i = 0; i < json.length; i++) {
  // First we need to create the td elements.
  const source = document.createElement('td');
  source.innerText = json[i]['source'];
  const name = document.createElement('td');
  name.innerText = json[i]['name'];
  const amount = document.createElement('td');
  amount.innerText = json[i]['amount'];
  
  //Then we need to create a tr to containt the tds
  const tr = document.createElement('tr');
  tr.appendChild(source);
  tr.appendChild(name);
  tr.appendChild(amount);
  
  //Finaly we need to add our tr to our tbody.
  tbody.appendChild(tr);
}
<table>
  <thead>
    <th>source</th>
    <th>name</th>
    <th>amount</th>
  </thead>
  <tbody id="myTable">
    <!-- the id is used to later refer to this tbody. -->
  </tbody>
</table>

</div>

I am just pasting a live working example for your help, you can modify based on your requirements. Actually, I think its a quick way to help someone. I am using a fake REST service available at https://jsonplaceholder.typicode.com/posts/.

I have already it in a page at https://hygull.github.io/pages/animations/ajax_data_fetch.html. If you wish you can inspect and see the code in body inside <script> & </script>. It is exactly like what you want. Just a little change required is, use source, name, amount in place of id, title, body etc. Also change the request URL.

Here is the example that you can modify and run at https://www.w3schools.com/code/tryit.asp?filename=G2FBIOPTDIQ6.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
<h2>POSTS EXAMPLE - RENDER RESPONSE FROM FAKE REST API</h2>
<a href="https://jsonplaceholder.typicode.com/posts/">https://jsonplaceholder.typicode.com/posts/</a>
<hr>
<table class="table table-condensed">
  <thead>
    <tr>
      <th>Id</th>
      <th>Title</th>
      <th>Body</th>
    </tr>
  </thead>

  <!-- TABLE BODY -->
  <tbody id="tbody">
  </tbody>
</table>
</div>

<script>
function setTable(){
    xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
            posts = JSON.parse(this.responseText)

            var postsText=""

            for (var i=0; i < posts.length; i++){
                postsText += "<tr>" + "<td>" + posts[i].id + "</td><td>" + posts[i].title + "</td><td>" + posts[i].body + "</td></tr>";
            }

            document.getElementById("tbody").innerHTML = postsText;
        }
    };
    xhttp.open("GET", "https://jsonplaceholder.typicode.com/posts/", true);
    xhttp.send();
}

setTable(); 
</script>
</body>
</html>

</div>