[英]Change HTML structure according to JSON response from a REST API with JQuery
我有一個 REST API,它返回一個像這樣的 JSON 對象
{
"id": 1,
"status": "open"
}
其中狀態可以是“打開”或“關閉”。 我在帶有 JQuery 函數的 HTML 頁面中調用此 API:
<html>
<body>
</body>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data){
});
});
</script>
如果返回的 JSON 對象的狀態為“打開”,我想更改我的 HTML 頁面如下
<html>
<body>
<p>THE QUESTION IS OPEN</p>
</body>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data){
});
});
</script>
否則,如果返回的 JSON 對象的狀態為“關閉”,我想更改我的 HTML 頁面如下
<html>
<body>
<p>THE QUESTION IS CLOSED</p>
</body>
<script>
$(document).ready(function() {
$.getJSON("http://localhost:8080/api/question/1", function(data){
});
});
</script>
使用 JQuery 實現這一目標的最佳方法是什么?
您可以使用$('body').prepend()
將數據放在打開的<body>
標簽之后
$(document).ready(function() { $.getJSON("http://localhost:8080/api/question/1", function(data) { if (data.status) { let str = `The Question is ${data.status}`.toUpperCase() $('body').prepend(`<p>${str}</p>`) } }); }); // for the example let data = { "id": 1, "status": "open" } if (data.status) { let str = `The Question is ${data.status}`.toUpperCase() $('body').prepend(`<p>${str}</p>`) }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
您的 JSON 對象中有id
和status
。 如果您要在同一頁面上為多個問題設置狀態段落,您可以這樣做:
$(document).ready( function() { $.getJSON("http://localhost:8080/api/question/1", function(data) { let statusParagraph = document.getElementById("status-" + data.id); let statusText; if (data.status === "open") { statusText = "THE QUESTION IS OPEN"; } else if (data.status === "closed") { statusText = "THE QUESTION IS CLOSED"; } statusParagraph.innerHTML = statusText; }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <body> <p id="status-1"></p> <p id="status-2"></p> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.