【问题标题】:Change HTML structure according to JSON response from a REST API with JQuery根据来自带有 JQuery 的 REST API 的 JSON 响应更改 HTML 结构
【发布时间】:2021-10-01 09:10:12
【问题描述】:

我有一个 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 实现这一目标的最佳方法是什么?

【问题讨论】:

  • 函数(数据){ if(data.status == "open") ? var statusText = "问题未解决" : var statusText = "问题已关闭"; document.getElementsByTagName("p")[0].innerHTML = statusText; }
  • 如果答案对您有帮助,请将其标记为正确。

标签: javascript jquery json rest


【解决方案1】:

您可以使用$('body').prepend() 将数据放在打开的&lt;body&gt; 标记之后

$(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>`)
}
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    您的 JSON 对象中有 idstatus。 如果您要在同一页面上有多个问题的状态段落,您可以这样做:

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

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 1970-01-01
      • 2021-01-08
      • 2019-11-17
      • 2021-05-27
      • 2016-11-11
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      相关资源
      最近更新 更多