【问题标题】:JSON not returning the actual data from the urlJSON 未从 url 返回实际数据
【发布时间】:2020-10-15 06:56:06
【问题描述】:

我正在尝试建立一个基本的 covid19 网站。我正在使用的代码仅在实际数据中返回 [object Object]。我在这里做错了什么?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.getJSON("https://api.covid19api.com/summary", function(result){
      $.each(result, function(i, field){
        $("div").append(field + " ");
      });
    });
  });
});
</script>
</head>
<body>

<button>Get JSON data</button>

<div></div>

</body>
</html>

【问题讨论】:

  • 查看$.each()的文档
  • 您无法在 DOM 中显示对象,尝试将 $("div").append(field + " "); 替换为 console.log(field); 您将看到数据是正确的,使用您可以使用的单个项目,例如 field.NewConfirmed跨度>

标签: javascript jquery json ajax


【解决方案1】:

那是因为您试图将 JavaScript 对象附加到 DOM。相反,看看你得到了什么数据(正如 cmets 中提到的,console.log)然后你可以相应地编辑你的附加部分。

【讨论】:

    【解决方案2】:

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      $("button").click(function(){
        $.getJSON("https://api.covid19api.com/summary", function(result){
          $.each(result.Countries, function(i, field){
            $("div").append("<span>"+JSON.stringify(field)+"</span></br>");
          });
        });
      });
    });
    </script>
    </head>
    <body>
    
    <button>Get JSON data</button>
    
    <div></div>
    
    </body>
    </html>

    【讨论】:

      【解决方案3】:

      在这里,我有一个示例答案,它附加了所有国家/地区列表。了解每条线路和功能它是如何工作的。我已经附加了国家列表,如何呈现我留给你的其余项目。不要气馁或失望;学习编程是一段旅程,而不是终点。

      注意https://cors-anywhere.herokuapp.com/ 如果您在 localhost 中运行它,则添加它以避免 CORS 的问题。如果您已托管该页面,则可以将其删除。

          $(document).ready(function(){
          $("button").on('click',function(){
          $.getJSON("https://cors-anywhere.herokuapp.com/https://api.covid19api.com/summary", function(result){
                     var obj=result;
                     var json = JSON.stringify(obj);
                     var s = JSON.parse(json);
                     s.Countries.map(function(c){
                           $("#result").append("<span>"+c.Country+"</span></br>");
                     })
                     console.log(s.Countries[0].Country);
          });
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-24
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多