【问题标题】:Need to get name data from JSON file需要从 JSON 文件中获取名称数据
【发布时间】:2018-01-05 01:24:47
【问题描述】:

我需要从 JSON 文件中获取名称,这段代码有什么问题? 我想从每个结果中获取名称值并将它们添加到正文中。

        <!DOCTYPE html>
        <html>
            <head>
                <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="crossorigin="anonymous"></script>
                <script>
                    $.ajax({ 
                   type: "GET",
                   dataType: "json",
                   url: "https://wger.de/api/v2/exercise.json?category=8&language=2",
                   success: function(data){
                       $.each(data,function(index,object){
                           $("body").append("<div>"+object.name +"</div><br/>")
                       })
                   }
                });
                </script>

            </head>

            <body>

            </body>
        </html>

【问题讨论】:

  • 如果您记录成功回调中的data 参数会是什么样子?
  • 显示json文件中的数据
  • @Axwell 发布 JSON 示例。您可能误读了结构。
  • @Barmar 我如何读取这个 JSON 文件的结构
  • 在浏览器中打开网址。如有必要,请使用 jsonlint.com 对其进行格式化。

标签: javascript html json getjson


【解决方案1】:

唯一的问题是您使用了错误的对象进行迭代。

如果你运行这个 sn-p 你可以在控制台上看到返回的对象。

$.ajax({ 
   type: "GET",
   dataType: "json",
   url: "https://wger.de/api/v2/exercise.json?category=8&language=2",
   success: function(data){
       console.log(data)
   }
});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

如您所见,您需要遍历data.results,所以这段代码应该可以工作:

$.ajax({ 
   type: "GET",
   dataType: "json",
   url: "https://wger.de/api/v2/exercise.json?category=8&language=2",
   success: function(data){
       if(data.results){
           $.each(data.results,function(index,object){
               $("body").append("<div>"+object.name +"</div><br/>")
           })
       }
   }
});

【讨论】:

  • $.each的参数中需要data.results
【解决方案2】:

提供给成功回调的data 参数以对象的形式出现,其结果属性是对象数组。

与其将整个data 对象传递给$.each,不如只给它一个结果数组,如下所示:

success: function(data){
    $.each(data.results, function(index, object){
        $("body").append("<div>"+object.name +"</div><br/>")
    })
}

【讨论】:

  • 这和图格的回答一样。
  • 我应该删除它@Barmar 吗?我不确定协议。我在编辑其他答案之前做了这个
  • 如果我自己的答案与其他人的答案基本相同,我通常会删除它,除非我在解释中添加了额外的内容。但我也不是在寻找声望的颠簸,我有很多空闲的。 :)
猜你喜欢
  • 1970-01-01
  • 2018-06-01
  • 2021-07-05
  • 2019-06-02
  • 2021-12-08
  • 2020-02-22
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多