【问题标题】:Looping through a JSON file with JavaScript but getting undefined output使用 JavaScript 循环遍历 JSON 文件但得到未定义的输出
【发布时间】:2016-10-03 02:58:14
【问题描述】:

我要从服务器获取一些 JSON 符号并使用 XMLHttpRequest(); 将其呈现在站点上。

这是文件 - http://www.adweb.agency/interview/api/animals

我已获取数据,可以在浏览器上查看。但是当我尝试将它放入一个 html 表格时,我得到一个充满未定义内容的表格。我花了至少 10 个小时阅读 JSON 表示法,并且对它的工作原理有很好的理解,但我的数据仍然未定义。当我将它与 w3schools 上的示例进行比较时,我发现我们的代码没有任何区别。当我尝试遍历数据并尝试部分获取数据时,似乎会出现问题。我研究过的一些例子表明,数据通常具有某种数组名称。当我从他们的服务器直接在浏览器中查看数据时,我在数据中看不到数组名称。我将使用 JavaScript,但不允许使用 JQuery。这适合我,因为我在这里学习,而不是简单地完成工作。这是我的功能。

function loadAnimals() {
    var animals = new XMLHttpRequest();
    animals.open("GET", "http://www.adweb.agency/interview/api/animals", true);
    animals.onreadystatechange = function () {
        if (animals.readyState == 4 && animals.status == 200) {
            var animalObject = JSON.parse(animals.responseText);
            var table = "<table>";
            var i;
            for (i = 0; i < animalObject.length; i++) {
                table += "<tr>" +
                    "<td>" + animalObject[i].Title + "</td>" +
                    "<td>" + animalObject[i].Description + "</td>" +
                    "<td>" + animalObject[i].Family + "</td>" +
                    "<td>" + animalObject[i].CollectiveNoun + "</td>" +
                    "</tr>";
            }
            table += "</table>";
            document.getElementById("animals").innerHTML = table;
        }
    }
    animals.send(null);
}     

【问题讨论】:

  • API 返回 XML(其中包含 JSON)而不是 JSON
  • 第一个问题是你要加载的文件是xml文件而不是json文件。
  • 我的理解是一个带有JSON格式的xml文件。我应该使用 resposeXML 吗?
  • 请在下面查看我的 html

标签: javascript html json html-table


【解决方案1】:

响应首先不是 JSON :)

响应的内容类型是 - Content-Type:application/xml;字符集=utf-8

您正在尝试读取 xml 文件并尝试打印 JSON 数据,因此遇到了问题。

【讨论】:

  • 这肯定是第一步。然后你就会知道你的json迭代逻辑有没有问题。
【解决方案2】:
"[{\"Id\":1,\"Title\":\"Baby Antelope\",\"Description\":\"An antelope is a member of a number of even-toed ungulate species indigenous to various regions in Africa and Eurasia. A group of antelope is called a herd.\",\"Family\":\"Bovidae\",\"CollectiveNoun\":\"Herd\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/1_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/1_thumb.jpg\"}},{\"Id\":2,\"Title\":\"Baby Sheep (Lamb)\",\"Description\":\"Sheep (Ovis aries) are quadrupedal, ruminant mammals typically kept as livestock. Numbering a little over one billion, domestic sheep are also the most numerous species of sheep.\",\"Family\":\"Bovidae\",\"CollectiveNoun\":\"Flock\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/2_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/2_thumb.jpg\"}},{\"Id\":3,\"Title\":\"Leopard\",\"Description\":\"The leopard is one of the five big cats in the genus Panthera. It is similar in appearance to the jaguar, but is smaller and more lightly built.\",\"Family\":\"Felidae\",\"CollectiveNoun\":\"Leap\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/3_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/3_thumb.jpg\"}},{\"Id\":4,\"Title\":\"Squirrel\",\"Description\":\"Squirrels are members of the family Sciuridae, consisting of small or medium-size rodents. Squirrels are indigenous to the Americas, Eurasia, and Africa, and have been introduced to Australia.\",\"Family\":\"Sciuridae\",\"CollectiveNoun\":\"Colony\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/4_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/4_thumb.jpg\"}},{\"Id\":5,\"Title\":\"Rooster\",\"Description\":\"A rooster, also known as a cockerel or cock, is a male gallinaceous bird, usually a male chicken. The term rooster originates in the United States, and the term is widely used throughout North America, as well as Australia and New Zealand.\",\"Family\":\"Phasianidae\",\"CollectiveNoun\":\"Brood\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/5_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/5_thumb.jpg\"}},{\"Id\":6,\"Title\":\"Duck\",\"Description\":\"Duck is the common name for a large number of species in the Anatidae family of birds which also includes swans and geese. Ducks are mostly aquatic birds, mostly smaller than the swans and geese, and may be found in both fresh water and sea water.\",\"Family\":\"Anatidae\",\"CollectiveNoun\":\"Flock\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/6_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/6_thumb.jpg\"}},{\"Id\":7,\"Title\":\"Rabbit\",\"Description\":\"Rabbits are small mammals in the family Leporidae of the order Lagomorpha, found in several parts of the world. Rabbits live in groups, and the best known species, the European rabbit, lives in underground burrows, or rabbit holes.\",\"Family\":\"Leporidae\",\"CollectiveNoun\":\"Berry\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/7_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/7_thumb.jpg\"}},{\"Id\":8,\"Title\":\"Dog\",\"Description\":\"The domestic dog is a domesticated canid which has been selectively bred for millennia for various behaviors, sensory capabilities, and physical attributes. Dogs perform many roles for people, such as hunting, herding, pulling loads, protection, assisting police and military, companionship, and, more recently, aiding handicapped individuals.\",\"Family\":\"Pack\",\"CollectiveNoun\":\"Canidae\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/8_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/8_thumb.jpg\"}},{\"Id\":9,\"Title\":\"Collared Peccary\",\"Description\":\"The collared peccary (Pecari tajacu) is a species of mammal in the family Tayassuidae found in North, Central, and South America. Although somewhat related to the pigs and frequently referred to as one, this species and the other peccaries are no longer classified in the pig family.\",\"Family\":\"Tayassuidae\",\"CollectiveNoun\":\"Parcel\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/9_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/9_thumb.jpg\"}},{\"Id\":10,\"Title\":\"Bee\",\"Description\":\"Bees are flying insects closely related to wasps and ants, known for their role in pollination and, in the case of the best-known bee species, the European honey bee, for producing honey and beeswax.\",\"Family\":\"Apoidea\",\"CollectiveNoun\":\"Swarm\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/10_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/10_thumb.jpg\"}},{\"Id\":11,\"Title\":\"Horse\",\"Description\":\"The horse (Equus ferus caballus) is one of two extant subspecies of Equus ferus. Humans began to domesticate horses around 4000 BC, and their domestication is believed to have been widespread by 3000 BC.\",\"Family\":\"Equidae\",\"CollectiveNoun\":\"Team\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/11_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/11_thumb.jpg\"}},{\"Id\":12,\"Title\":\"European Robin\",\"Description\":\"The European robin (Erithacus rubecula), most commonly known in Anglophone Europe simply as the robin, is a small insectivorous passerine bird, specifically a chat, that was formerly classed as a member of the thrush family (Turdidae), but is now considered to be an Old World flycatcher.\",\"Family\":\"Muscicapidae\",\"CollectiveNoun\":\"Flock\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/12_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/12_thumb.jpg\"}},{\"Id\":13,\"Title\":\"Lemur\",\"Description\":\"Lemurs are a clade of strepsirrhine primates endemic to the island of Madagascar. The word lemur derives from the word lemures (ghosts or spirits) from Roman mythology and was first used to describe a slender loris due to its nocturnal habits and slow pace.\",\"Family\":\"Lemuroidea\",\"CollectiveNoun\":\"Conspiracy\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/13_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/13_thumb.jpg\"}},{\"Id\":14,\"Title\":\"Wild Boar\",\"Description\":\"The wild boar (Sus scrofa), also known as the wild swine or Eurasian wild pig is a suid native to much of Eurasia, North Africa, and the Greater Sunda Islands. Human intervention has spread its range further, making the species one of the widest-ranging mammals in the world, as well as the most widely spread suiform.\",\"Family\":\"Suidae\",\"CollectiveNoun\":\"Sounder\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/14_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/14_thumb.jpg\"}},{\"Id\":15,\"Title\":\"Peacock\",\"Description\":\"The term peacock is properly reserved for the male; the female is known as a peahen, and the immature offspring are sometimes called peachicks. The male has very long tail feathers with eye-like markings that can be erected and fanned out in display.\",\"Family\":\"Phasianidae\",\"CollectiveNoun\":\"Muster\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/15_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/15_thumb.jpg\"}},{\"Id\":16,\"Title\":\"Raccoon\",\"Description\":\"The raccoon is a medium-sized mammal native to North America. Two of the raccoon's most distinctive features are its extremely dexterous front paws and its facial mask, which are themes in the mythology of several Native American ethnic groups.\",\"Family\":\"Procyonidae\",\"CollectiveNoun\":\"Gaze\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/16_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/16_thumb.jpg\"}},{\"Id\":17,\"Title\":\"Fox\",\"Description\":\"Foxes are small-to-medium-sized, omnivorous mammals belonging to several genera of the Canidae family. Foxes are slightly smaller than a medium-size domestic dog, with a flattened skull, upright triangular ears, a pointed, slightly upturned snout, and a long bushy tail (or brush).\",\"Family\":\"Canidae\",\"CollectiveNoun\":\"Leash\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/17_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/17_thumb.jpg\"}},{\"Id\":18,\"Title\":\"Addax (White Antelope)\",\"Description\":\"The addax is an antelope of the genus Addax, that lives in the Sahara desert. The addax mainly eats grasses and leaves of any available shrubs, leguminous herbs and bushes.\",\"Family\":\"Bovidae\",\"CollectiveNoun\":\"Herd\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/18_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/18_thumb.jpg\"}},{\"Id\":19,\"Title\":\"Kitten\",\"Description\":\"A kitten (also known as a kitty or kitty cat) is a juvenile cat. After being born, kittens are totally dependent on their mother for survival and do not normally open their eyes until after seven to ten days.\",\"Family\":\"Felidae\",\"CollectiveNoun\":\"Kindle\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/19_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/19_thumb.jpg\"}},{\"Id\":20,\"Title\":\"Turtle\",\"Description\":\"Turtles are reptiles of the order Testudines (or Chelonii) characterised by a special bony or cartilaginous shell developed from their ribs and acting as a shield.\",\"Family\":\"Cheloniidae\",\"CollectiveNoun\":\"Bale\",\"Width\":800,\"Height\":600,\"ImageURLs\":{\"FullSize\":\"http://adweb.agency/interview/images/animals/20_full.jpg\",\"Thumb\":\"http://adweb.agency/interview/images/animals/20_thumb.jpg\"}}]"

这是你的响应,它不是 JSON 字符串,所以你应该在使用 JSON.parse 之前对其进行解码,就像这样:

function loadAnimals() {
    var animals = new XMLHttpRequest();
    animals.open("GET", "http://www.adweb.agency/interview/api/animals", true);
    animals.onreadystatechange = function () {
        if (animals.readyState == 4 && animals.status == 200) {
            var animalObject = JSON.parse(decodeURIComponent(animals.responseText));
            var table = "<table>";
            var i;
            for (i = 0; i < animalObject.length; i++) {
                table += "<tr>" +
                    "<td>" + animalObject[i].Title + "</td>" +
                    "<td>" + animalObject[i].Description + "</td>" +
                    "<td>" + animalObject[i].Family + "</td>" +
                    "<td>" + animalObject[i].CollectiveNoun + "</td>" +
                    "</tr>";
            }
            table += "</table>";
            document.getElementById("animals").innerHTML = table;
        }
    }
    animals.send(null);
}

【讨论】:

  • 这是我能看到的唯一区别。我错过了吗?
  • 对不起,这是我的错,你可以使用 JSON.parse 两次,像这样: JSON.parse(JSON.parse(animals.responseText))
  • 试过了。没有骰子。
【解决方案3】:

hi 请在一个单一的文件中尝试这个html保存并运行我有结果

 <!DOCTYPE html>
<html>
<body>

<div id="animals"></div>

<script>
loadAnimals()

 function loadAnimals(){ 

              var animals = new XMLHttpRequest(); 
              animals.open("GET", "http://www.adweb.agency/interview/api/animals", true ); 

       animals.onreadystatechange = function(){      

                                     if ( animals.readyState == 4 && animals.status == 200 )  {

                                        var animalObject = JSON.parse(animals.responseText);
                                        var animallength = JSON.parse(animalObject)

                                        var table = "<table>";
                                        var i;

                                        for( i = 0; i < animallength.length ; i ++ ) {

                                             table += "<tr>" +
                                            "<td>" + animallength[i].Title + "</td>" +
                                            "<td>" + animallength[i].Description + "</td>" + 
                                            "<td>" + animallength[i].Family + "</td>" +
                                            "<td>" + animallength[i].CollectiveNoun + "</td>" +
                                            "</tr>";
                                            }

                                            table += "</table>";
                                            document.getElementById("animals").innerHTML = table;

                                           }
                                         }
                               animals.send(null);    
                             }   
</script>

</body>
</html>

【讨论】:

  • 我们赢了!谢谢你。这行得通。我会比较我们的代码一个学习!谢谢。
  • 您在我的脚本开头添加了 loadAnimals()。这是怎么做到的?
  • 这不是因为我添加了 var animallength = JSON.parse(animalObject) 并且在 for 循环中我使用了可变长度而不是 animalObject 长度
  • 刚试过这个......我在控制台(FF)中得到这个......阻止加载混合活动内容“adweb.agency/interview/api/animals
  • 请随时编辑这个 plunker 并尝试使其工作......plnkr.co/edit/O2eCQpByYTLFovOWZLbZ?p=preview
【解决方案4】:

你好,你犯了一个简单的错误

 function loadAnimals(){ 

          var animals = new XMLHttpRequest(); 
          animals.open("GET", "http://www.adweb.agency/interview/api/animals", true ); 

   animals.onreadystatechange = function(){      

                                 if ( animals.readyState == 4 && animals.status == 200 )  {

                                    var animalObject = JSON.parse(animals.responseText);
                                    var animallength = JSON.parse(animalObject)

                                    var table = "<table>";
                                    var i;

                                    for( i = 0; i < animallength.length ; i ++ ) {

                                         table += "<tr>" +
                                        "<td>" + animallength[i].Title + "</td>" +
                                        "<td>" + animallength[i].Description + "</td>" + 
                                        "<td>" + animallength[i].Family + "</td>" +
                                        "<td>" + animallength[i].CollectiveNoun + "</td>" +
                                        "</tr>";
                                        }

                                        table += "</table>";
                                        document.getElementById("animals").innerHTML = table;

                                       }
                                     }
                           animals.send(null);    
                         }   

你必须使用该长度解析并存储在一个变量中,我认为这对我有用,所以尝试替换上面的函数

【讨论】:

  • 这有帮助。我的循环现在停在正确的位置。但数据仍未定义。
  • 我应该尝试什么来代替 JSON.parse?
  • 你检查了我的 html 它工作正常并显示结果
  • 是的。在我看到它的前 10 分钟你就做对了。非常感谢。
猜你喜欢
  • 2013-02-19
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多