0
votes

I want to be able to use the REST API below and display data on a single HTML page.

This is the API (response) from a database connection function in my Django project.

URL: http://127.0.0.1:8000/api/v1/test/

API output:
{
    "message": "Success !",
    "server": "Connection established from ('PostgreSQL 12.7, compiled by Visual C++ build 1914, 64-bit',)"
}

I tried to display the data using AJAX. However, the data does not appear on the page. This is my attempt:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>API Calls Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>

<body>
    <div class="container-fluid">
        <h3>Test Output</h3>
        <br></br>
        <table class="table table-sm">
            <tr>
                <th>Output</th>
            </tr>
            <tbody id="divBody"></tbody>
        </table>
    </div>
</body>
<script>
    $(document).ready(function () {
            BindConnection();
        });

    function BindConnection(){
        $.ajax({
            type:"GET",
            dataType: "JSON",
            url: "http://127.0.0.1:8000/api/v1/test", 
            success: function(data){
                console.log(data);

                var str = "";
                var totalLength = data.length;
                
                for (let i=0; i < totalLength; i++){
                    str += "<tr>" +
                        "<td>" + data[i].server + "</td>"
                    "</tr>"
                }
                $("#divBody").append(str)
            }
        });
    }
</script>

Note: The result can be displayed on the console and there is no error.

Sorry for my poor attempt, cause I am still new with Django, REST API, and Javascript (AJAX). I have tried several attempts but I cannot make it.

Could you please help me to answer this problem? Thank you!

enter image description here

1

1 Answers

0
votes

i think the following line who causing the problem

var totalLength = data.length;

it seems the dictionary has no attribute length as the api response with dictionary so you need to deal with it as a dictionary not array if you tried to add line

console.log(totalLength)

it will be undifiend value so no looping happening