繁体   English   中英

如何在 Django 中使用 AJAX 显示 rest api?

[英]How to display rest api using AJAX in Django?

我希望能够使用下面的 REST API 并在单个 HTML 页面上显示数据。

这是我的Django project数据库连接函数的 API(响应)。

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',)"
}

我尝试使用 AJAX 显示数据。 但是,该数据不会出现在页面上。 这是我的尝试:

<!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>

注意:可以在控制台显示结果,没有错误。

抱歉,我的尝试很糟糕,因为我还是 Django、REST API 和 Javascript (AJAX) 的新手。 我已经尝试了几次,但我做不到。

你能帮我回答这个问题吗? 谢谢!

在此处输入图片说明

我认为导致问题的以下行

var totalLength = data.length;

似乎字典没有属性列表作为带有字典的 api 响应,因此如果您尝试添加行,则需要将其作为字典而不是数组来处理

console.log(totalLength)

这将是 undifiend 值所以没有循环幸福

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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