weixin_33690963 2017-01-16 08:04 采纳率: 0%
浏览 28

JSON和HTML的麻烦

i'm currently having some troubles with displaying the information from a JSON file to html. I'm currently using AJAX to get the data from the JSON file. The main problem that i'm facing is with displaying all the data into one div.

    function Test(){
  request.open('GET','/json/anime.json');
  request.onreadystatechange = function() {
    if((request.readyState===4) && (request.status===200)) {
      var json = JSON.parse(request.responseText);
      for(var title in json.Title ) {
        for(var ep in json.Episode) {
          for(var img in json.Image) {
            for(var link in json.Link) {
              _title = json.Image[title];
              episode = json.Image[ep];
              image = json.Image[img];
              _link = json.Image[link];
              var div = document.createElement('div');
              div.className = 'card card-inverse';
              div.innerHTML = `<a href="${_link}"><img class="card-img img-fluid img-responsive" src="${image}" data-toggle="modal"></a>`;
              document.getElementById('anime').appendChild(div);
            }
          }
        }
      }
    }
  }
  request.send();
}

The JSON file looks like this...

{
    Episode: [
        ...    
    ],
    Image: [
        ...
    ],
    Link: [
        ...
    ],
    Title: [
        ...
    ]
}

The way above is working if i'm only looping over one of the four arrays, however crashes chrome when trying to do the above task.

Any help would be appreciated.

Thanks

  • 写回答

1条回答 默认 最新

  • weixin_33737774 2017-01-16 10:18
    关注

    I decided to take a different approach moving away from ajax a little and moving more towards jquery. Below is what has so far worked out for me. Thanks to the people who commented above, really helped me think of ways to tackling it.

    function DisplayCards() {
      var i = 0;
      $.getJSON('/json/anime.json', function(data) {
          $.each(data, function(index) {
            for(key in data[index]){
              e = data.Image.length;
              console.log(e);
              if(i < e)
              {
                image = data.Image[key];
                link = data.Link[key];
    
                console.log(i += 1);
                var div = document.createElement('div');
                div.className = 'card card-inverse';
                div.innerHTML = `<a href="${link}"><img class="card-img img-fluid img-responsive" src="${image}" data-toggle="modal"></a>`;
                var p = document.createElement('p');
                p.innerHTML = 'id="wrapper" class="text"';
                document.getElementById('anime').appendChild(div);
              }
            }
            console.log(data);
    
    
          });
      });
    }
    
    评论

报告相同问题?