【发布时间】:2021-12-27 06:39:44
【问题描述】:
我希望能够使用下面的 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) 的新手。我已经尝试了几次,但我无法做到。
你能帮我回答这个问题吗?谢谢!
【问题讨论】:
标签: javascript jquery django ajax