如何从API中的Json数据中获取数据

时间:2017-05-08 05:03:25

标签: javascript json ajax

我想通过使用Ajax调用JSON数据来获取具有name标记的数据。但是现在函数showCard无法正常工作。如何获取具有name标记的数据?当您点击img found时,我想从API获取数据,并通过innerHTML显示其名称。但是现在单击它时没有任何反应。 附:其id添加在函数populatePokedex中。希望这个问题有道理。感谢。

(function() {
'use strict';

window.onload = function(){
    populatePokedex(); // <- This works correctly

    var $foundPics = document.getElementsByClassName("found");
    for(var i = 0; i < $foundPics.length; i++){
        $foundPics[i].onclick = showCard;
    }
};



// populate Pokedex
function populatePokedex() {

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all");
    xhr.onload = function(){
        if (this.status == 200) {
            var picArr = this.responseText.split("\n");
            for(var i=0; i < picArr.length; i++){
                var eachName = picArr[i].split(":");
                var spriteurl = "/Pokedex/sprites/" + eachName[1];
                var imgClass = 'sprite';
                if(eachName[1]==='bulbasaur.png' || eachName[1]==='charmander.png' || eachName[1]==='squirtle.png'){
                    imgClass += ' found';
                } else {
                    imgClass += ' unfound';
                }
                document.getElementById("pokedex-view").innerHTML += "<img src=\"" + spriteurl + "\" id=\"" + eachName[0] + "\" class=\"" + imgClass + "\">";
            }
        } else {
            document.getElementById("pokedex-view").innerHTML = "ERROR: Status: " + this.status + ", " + this.statusText;
        }
    };
    xhr.onerror = function(){
        document.getElementById("pokedex-view").innerHTML = "ERROR";
    };
    xhr.send();
}


// if the pokemon is found, it shows the data of the pokemon
function showCard() {
    var xhr = new XMLHttpRequest();
    var url = "https://webster.cs.washington.edu/pokedex/pokedex.php?pokemon=" + this.id;
    xhr("GET", url);
    xhr.onload = function(){
        var data = JSON.parse(this.responseText);
        var pokeName = document.getElementsByClassName("name");
        for(var i=0; i < pokeName.length; i++){
            pokeName[i].innerHTML = data.name;
        }
    };
    xhr.onerror = function(){
        alert("ERROR");
    };
    xhr.send();

}


})();

下面列出了部分HTML;

  <div id="my-card">

    <div class="card-container">
      <div class="card">
        <h2 class="name">Pokemon Name</h2>
        <img src="icons/fighting.jpg" alt="weakness" class="weakness" />
      </div>
    </div>
  </div>

  <!-- You populate this using JavaScript -->
  <div id="pokedex-view"></div>

2 个答案:

答案 0 :(得分:2)

当我使用你的网址:https://webster.cs.washington.edu/pokedex/pokedex.php?pokemon=mew时,我得到了这些数据:

{"name":"Mew","hp":160,"info":{"id":"151","type":"psychic","weakness":"dark","description":"Its DNA is said to contain the genetic codes of all Pokemon."},"images":{"photo":"images\/mew.jpg","typeIcon":"icons\/psychic.jpg","weaknessIcon":"icons\/dark.jpg"},"moves":[{"name":"Amnesia","type":"psychic"},{"name":"Psychic","dp":90,"type":"psychic"}]}

假设您要显示单词mew,data.name或data ['name']可以正常工作。 我怀疑的是document.getElementsByClassName("name").innerHTML 不存在或沿着那条线的东西。我可以看到运行该功能时出现的错误消息,还是显示您的HTML部分?

答案 1 :(得分:2)

您在JS showCard

中遇到了一些问题

我编写了一个简单的解决方案。我在代码中添加了一些简短的解释(作为注释)

&#13;
&#13;
(function() {
  'use strict';

  window.onload = function() {
    populatePokedex(); // <- This works correctly
    
    // adding event listeners to dynamically added nodes.
    document.querySelector('body').addEventListener('click', function(event) {
      // need to target only elements with class found (but unfound would also match the indexOf below, so we changed the name of the matching class slightly)
      if (event.target.className.toLowerCase().indexOf('founded') != -1) {
        showCard();
      }
    });
  };


  // populate Pokedex
  function populatePokedex() {

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all");
    xhr.onload = function() {
      if (this.status == 200) {
        var picArr = this.responseText.split("\n");
        for (var i = 0; i < picArr.length; i++) {
          var eachName = picArr[i].split(":");
          var spriteurl = "https://webster.cs.washington.edu/pokedex/sprites/" + eachName[1];
          var imgClass = 'sprite';
          if (eachName[1] === 'bulbasaur.png' || eachName[1] === 'charmander.png' || eachName[1] === 'squirtle.png') {
            imgClass += ' founded';
          } else {
            imgClass += ' unfound';
          }
          document.getElementById("pokedex-view").innerHTML += "<img src=\"" + spriteurl + "\" id=\"" + eachName[0] + "\" class=\"" + imgClass + "\">";
        }
      } else {
        document.getElementById("pokedex-view").innerHTML = "ERROR: Status: " + this.status + ", " + this.statusText;
      }
    };
    xhr.onerror = function() {
      document.getElementById("pokedex-view").innerHTML = "ERROR";
    };
    xhr.send();
  }

  // if the pokemon is found, it shows the data of the pokemon
  function showCard() {
    
    var xhr = new XMLHttpRequest();
    // since you are in a click event, use the target's id instead
    var url = "https://webster.cs.washington.edu/pokedex/pokedex.php?pokemon=" + event.target.id;
    // there was an error here
    xhr.open("GET", url);
    xhr.onload = function() {
      // parse the response text into JSON
      var data = JSON.parse(this.responseText);
      // update the element with this id with a new value from the response data
      document.getElementById("pokemon-name").innerHTML = data.name;
    };
    xhr.onerror = function() {
      alert("ERROR");
    };
    xhr.send();

  }




})();
&#13;
.founded:hover {
  cursor: pointer;
}

.founded {
  border: 1px solid green;
}
&#13;
<div id="my-card">

  <div class="card-container">
    <div class="card">
      <h2 id="pokemon-name" class="name">Pokemon Name</h2>
      <img src="https://webster.cs.washington.edu/pokedex/icons/fighting.jpg" alt="weakness" class="weakness" />
    </div>
  </div>
</div>

<!-- You populate this using JavaScript -->
<div id="pokedex-view"></div>
&#13;
&#13;
&#13;