简体   繁体   中英

Convert json output to HTML table

I have a simple html page that has a form which takes input and upon clicking the button, it sends GET request to the backend server. I receive the response from the backend server in json format. My html file is as follows

<!DOCTYPE html>
<html>
<br/><br/><br/><br/>
<body>
<form action="http://localhost:9000/parsehtml" method="get">

    <h3Enter url :</h3>
    <input type="text" name="url" placeholder="http://example.com" style="width: 600px"><br>
    <br/><br/>
    <input type="submit" name="Get Website Statistics" style="width: 20em;  height: 2em;">
</form>
</body>
</html>

Now, I get redirected to another page on clicking submit button and a json response gets displayed as follows

{ 
   "htmlVersion":"HTML5",
   "title":"Example Title",
   "headings":[ 
      { 
         "tag":"h1",
         "count":1
      },
      { 
         "tag":"h2",
         "count":2
      },
      { 
         "tag":"h4",
         "count":2
      },
      { 
         "tag":"h5",
         "count":4
      }
   ],
   "internalLinks":{ 
      "count":1,
      "links":[ 
         { 
            "tagName":"a",
            "link":"https://www.example.de/"
         }
      ]
   },
   "externalLinks":{ 
      "count":66,
      "links":[ 
         { 
            "tagName":"a",
            "link":"https://abo.example.de/?bste"
         }
      ]
   },
   "containsLoginForm":true
}

I want to convert this json to a HTML table format. I am a complete newbie to javascript and html and am completely confused as to where I need to write a script to capture this json and convert it to a HTML table.

Any inputs are highly appreciated. TIA !!!

You haven't posted any javascript, but it sounds like you need to call event.prventDefault() in whatever code listens for the click:

 document.getElementById("myAnchor").addEventListener("click", function(event){
  event.preventDefault()
});

Assuming you cannot edit the backend, my best guess would be to capture the form submit event and send an AJAX request, then parse the response and display the table accordingly.

This assuming the form is hosted on the same server the form is going to be submitted to, otherwhise you will have to proxy the requests.

However you need to consider the following:

  • Is the table based on user input? If so, is that input sanitized server side?
  • How is your JSON file structured?

I suggest you to learn about HTML Tables JSON parsing in JavaScript and DOM manipulation in Javascript .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM