简体   繁体   中英

Change HTML structure according to JSON response from a REST API with JQuery

I have a REST API that returns a JSON object like this

{
 "id": 1,
 "status": "open"
}

where status can be "open" or "closed". I call this API in an HTML page with a JQuery function:

<html>
<body>
</body>
<script>

    $(document).ready(function() {
          $.getJSON("http://localhost:8080/api/question/1", function(data){
           
    
          });
        });
</script>

If status from returned JSON object is "open", I want to change my HTML page as following

<html>
    <body>
<p>THE QUESTION IS OPEN</p>
    </body>
    <script>
    
        $(document).ready(function() {
              $.getJSON("http://localhost:8080/api/question/1", function(data){
               
        
              });
            });
    </script>

Otherwise, if status from returned JSON object is "closed", I want to change my HTML page as following

<html>
    <body>
<p>THE QUESTION IS CLOSED</p>
    </body>
    <script>
    
        $(document).ready(function() {
              $.getJSON("http://localhost:8080/api/question/1", function(data){
               
        
              });
            });
    </script>

What is the best way to achieve this with JQuery?

You can use $('body').prepend() to put the data right after the open <body> tag

 $(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>

You have both id and status in your JSON object. If you are going to have status paragraphs for several questions on the same page, this is the way you could do it:

 $(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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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