Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

javascript - Converting JSON to HTML Document

So I have an AJAX call that works perfectly and receives SharePoint List items as JSON. I want to populate the JSON object(s) to a printable HTML document, but I am unsure how to go about it because I don't want to post it to a table as that is not how I want the layout to look.

Here is my JS call to read from the list:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function loadData(source, url) {
  return fetch(url, { headers: { accept: "application/json; odata=verbose" } }) // make request
    .then((r) => r.json()) // parse JSON
    .then((data) => data.d.results) // unwrap to get results array
    .then((results) => {
      results.forEach((r) => (r.source = source)); // add source to each item
      return results;
    });
}

window.addEventListener("load", function () {
  Promise.all([
    loadData("WeeklyReport1", _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('WeeklyReport1')/items?$select=Team,WeekOf,OffensiveReport,DefensiveReport,SpecialTeamsReport"),
    loadData("WeeklyReport2", _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('WeeklyReport2')/items?$select=Team,WeekOf,OffensiveReport,DefensiveReport,SpecialTeamsReport"),
  ])
    .catch((err) => {
      alert("Error: " + err);
      console.error(err);
    });
});
</script>

Here is the JSON it returns:

{
   "d":{
      "results":[
         {
            "__metadata":{
               "id":"random number string",
               "uri":"I removed this because it is a sharepoint link",
               "etag":""1"",
               "type":"SP.Data.WeeklyReport1ListItem"
            },
            "Team":"Cowboys",
            "WeekOf":"2021-01-15T05:00:00Z",
            "OffensiveReport":"Insert something about the offensive report",
            "DefensiveReport":"Insert something about the defensive report",
            "SpecialTeamsReport":"Insert something about the special teams report"
         }
      ]
   }
}

Based on the JSON above this, this is how I want to place it in HTML but I have zero clue how to:


Cowboys(underline team name)

Offensive Report

  • Insert something about the offensive report

Defensive Report

  • Insert something about the defensive report

Special Teams Report

  • Insert something about the special teams report

If more than one team, insert next here

To Reiterate my question. How can I take this object pulled from this loadData and populate it to an HTML Document in the format I demonstrated above?

UPDATE: I UPDATED MY JS TO THIS JS WHEN IT POSTS IT IS SO SCREWED UP

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function loadData(source, url) {
  return fetch(url, { headers: { accept: "application/json; odata=verbose" } }) // make request
    .then((r) => r.json()) // parse JSON
    .then((data) => data.d.results) // unwrap to get results array
    .then((results) => {
      results.forEach((r) => (r.source = source)); // add source to each item
      return results;
    });
}

window.addEventListener("load", function () {
  Promise.all([
    loadData("WeeklyReport1", _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('WeeklyReport1')/items?$select=Team,WeekOf,OffensiveReport,DefensiveReport,SpecialTeamsReport"),
    loadData("WeeklyReport2", _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('WeeklyReport2')/items?$select=Team,WeekOf,OffensiveReport,DefensiveReport,SpecialTeamsReport"),
  ])
  .then(([r1, r2]) => {
      const objItems = r1.concat(r2);
      var tableContent =
        '<table id="weekReport" style="width:100%"><thead><tr><td><strong>NFL Weekly Report</strong></td></tr>' +
        "<tr><td><strong>Team</strong></td></tr>" +
        "<tr><td><strong>Offensive Report</strong></td></tr>" +
        "<tr><td><strong>Defensive Report</strong></td></tr>" +
        "<tr><td><strong>Special Teams Report</strong></td></tr>" +
        "</thead><tbody>";

      for (var i = 0; i < objItems.length; i++) {
        tableContent += "<tr>";
        tableContent += "<td>" + objItems[i].Team + "</td>";
        tableContent += "</tr>";
        tableContent += "<tr>";
        tableContent += "<td>" + objItems[i].OffensiveReport + "</td>";
        tableContent += "</tr>";
        tableContent += "<tr>";
        tableContent += "<td>" + objItems[i].DefensiveReport + "</td>";
        tableContent += "</tr>";
        tableContent += "<tr>";
        tableContent += "<td>" + objItems[i].SpecialTeamsReport + "</td>";
        tableContent += "<tr>";
        tableContent += "</tr>";
      }
      $("#reports").append(tableContent);
    })
    .catch((err) => {
      alert("Error: " + err);
      console.error(err);
    });
});
</script>
<div id="WeeklyReport">
   <table id='weekReport' style="width: 100%;">
     <tr>
       <td>
          <div id="reports" style="width: 100%"></div>
      </td>
    </tr>
 </table>
</div>

This is how it turns out: enter image description here

question from:https://stackoverflow.com/questions/65835499/converting-json-to-html-document

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a very open-ended question. Since this is effectively using HTML to layout a template for some data, you could use a templating language like Mustache.js:

Add Mustache.js to your page, add the #target element we will render to, and create a function to render the template to the page as HTML:

/* 
 * Write the JSON data to a Mustache template and then
 * render the resulting HTML to the #target element.
 */
function renderData(data) {
  fetch('template.mustache')
    .then(response => response.text())
    .then(template => {
      const rendered = Mustache.render(template, data);
      document.getElementById('target').innerHTML = rendered;    
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/4.1.0/mustache.min.js"></script>
<div id="target" ></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...