Get data from AJAX API and display it in HTML document

I'm doing some troubleshooting on some API code.

We want to take from the XML format brought back in the API call and convert it into JSON. To help me work through this manipulation, I want to see what the data looks like, so I'm simply trying to get it to print into the body of an HTML document. Here is the HTML code which shows nothing, but Response Data when opened in a browser:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
    <h2> Response Data </h2>
    <!-- AJAX API Call -->

    <script> 
    {
        var settings = {
            "async": true,
            "crossDomain": true,
            "url": "https://qualysapi.qg2.apps.qualys.com/api/2.0/fo/scan/?action=list",
            "method": "GET",
            "headers": {
                "Authorization": "#############################################",
                "Cache-Control": "no-cache",
            }
        }

        $.ajax(settings).done(function (response) {
            $('body').append(response);
        });
    }
    </script>
</body>  

Is there a better way to do this?

2 answers

  • answered 2018-01-11 20:48 daddygames

    console.log() outputs the information to the browser console (developer tools). You need to direct the output to an element on the page. The following, using JQuery, appends the response to the body element:

    $.ajax(settings).done(function (response) {
        $('body').append(response);
    });
    

  • answered 2018-01-11 20:49 Kafoso

    console.log outputs things in the Console/Developer Tools. Not inside the HTML (DOM).

    What you want to do is manipulate the DOM. The placement of your Javascript code does not mean it will be output within the <body> tag.

    What you need is to iterate over the contents of your response object (should be JSON or XML), and then append nodes of text or even children DOM nodes to the <body> tag.

    Also, the $.ajax function, you are utilizing, uses the jQuery library. So you need to include that - either a local copy or via a CDN - in your <head> tag. Or at least before you call it in your custom Javascript code.

    This is very fundamental and you can easily find many guides via Google on how to implement this.