【问题标题】:Problem getting HTML to display after forEach loop在 forEach 循环后显示 HTML 的问题
【发布时间】:2020-08-15 23:27:30
【问题描述】:

希望有人能帮忙。这个小项目的目标是搜索电影数据库 OMDB,并在搜索栏下方显示获取的结果。当我尝试对返回的结果使用 forEach 循环时,我感觉代码会中断,但我找不到错误。感谢您的每一次帮助!谢谢!

var httpRequest = new XMLHttpRequest();

      httpRequest.onload = function() {
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
          if (httpRequest.status === 200) {
            var response = JSON.parse(httpRequest.responseText).Search;
            var body = document.getElementsByTagName("body");
            response.forEach(function (element, index) {
             body.appendChild(" <img src="+element[index].Poster+"/>" +
              "<p>Title: <a href = 'https://www.imdb.com/title/"+element[index].imdbID+"' >" +element[index].Title+ "</a></p>" +
              "<p>Year: "+ element[index].Year+"</p>" +
              "<p>Type: "+element[index].Type+"</p>");
          });



          } else {
            console.log(httpRequest.statusText);
          }
        }
      };


      httpRequest.onerror = function() {
        console.log(httpRequest.statusText);
      };


var searchMovie = function () {
  var input = document.querySelector('input').value;
  if (input) {  


          httpRequest.open('GET', 'https://www.omdbapi.com/?s=' + input + '&plot=short&apikey=b7da8d63');
          httpRequest.send(null);

}
};

【问题讨论】:

  • document.getElementsByTagName() 返回节点列表而不仅仅是一个节点,因此您需要获取第一个是 body 元素,最好使用 .querySelector("body") 甚至 document.body
  • 如果您可以发布您看到的错误,将会很有帮助。

标签: javascript json api foreach


【解决方案1】:

这是一个假设您要返回一系列电影的工作示例。

const response =  JSON.parse('{"Search":[{"Title":"The Town","Year":"2010","imdbID":"tt0840361","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMTcyNzcxODg3Nl5BMl5BanBnXkFtZTcwMTUyNjQ3Mw@@._V1_SX300.jpg"},{"Title":"Ghost Town","Year":"2008","imdbID":"tt0995039","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMTQyODQ4MzYxN15BMl5BanBnXkFtZTcwOTQ1MDczMw@@._V1_SX300.jpg"},{"Title":"Cougar Town","Year":"2009–2015","imdbID":"tt1441109","Type":"series","Poster":"https://m.media-amazon.com/images/M/MV5BMTQyMDI2MDM5NF5BMl5BanBnXkFtZTgwOTcyNDE5MDE@._V1_SX300.jpg"},{"Title":"New in Town","Year":"2009","imdbID":"tt1095174","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMzAxNzU4MDE1Nl5BMl5BanBnXkFtZTcwOTQ0NDcwMg@@._V1_SX300.jpg"},{"Title":"Mr. Deeds Goes to Town","Year":"1936","imdbID":"tt0027996","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BNzdiMDVkNmMtNDI0Ny00MTQ5LWEwNjAtODQxOGNjOTZmMGVmL2ltYWdlXkEyXkFqcGdeQXVyMDI2NDg0NQ@@._V1_SX300.jpg"},{"Title":"On the Town","Year":"1949","imdbID":"tt0041716","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BNjk0YmVlNTQtZDg0NC00MGYyLWFhYTMtMTBlMzFkYjczMDMyXkEyXkFqcGdeQXVyMDI2NDg0NQ@@._V1_SX300.jpg"},{"Title":"The Town That Dreaded Sundown","Year":"2014","imdbID":"tt2561546","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMTUwNzUyNjEwM15BMl5BanBnXkFtZTgwOTk3MTc2MjE@._V1_SX300.jpg"}],"totalResults":"1588","Response":"True"}');

// Get the body, which is the first element in the array
//  returned by document.getElementsByTagName()
var body = document.getElementsByTagName("body")[0];
var movie;
response.Search.forEach(function (element) {
  // Create a new element to append
  movie = document.createElement('div');

  // Add HTML contents to new element
  movie.innerHTML = 
              "<img src="+element.Poster+"/>" +
              "<p>Title: <a href = 'https://www.imdb.com/title/"+element.imdbID+"' >"+element.Title+ "</a></p>" +
              "<p>Year: "+element.Year+"</p>" +
              "<p>Type: "+element.Type+"</p>";

   // Append new element
   body.appendChild(movie);
});
<html>
<head></head>
<body>
</body>
</html>

【讨论】:

    【解决方案2】:

    var httpRequest = new XMLHttpRequest();
    
              httpRequest.onload = function() {
                if (httpRequest.readyState === XMLHttpRequest.DONE) {
                  if (httpRequest.status === 200) {
                    var response = JSON.parse(httpRequest.responseText).Search;
                    var body =document.getElementById('main')
                   body.innerHTML = ""
                    //document.getElementsByTagName("body");
                    response.forEach(function (element, index) {
                    var img=document.createElement('img')
        img.src=element.Poster
    
        var p1=document.createElement('p')
        p1.textContent='Title :'
    
        var a=document.createElement('a')
        a.textContent=element.Title
        a.href=`https://www.imdb.com/title/${element.imdbID}`
        p1.appendChild(a)
    
        var p2=document.createElement('p')
        p2.textContent=`Year: ${element.Year}`
    
        var p3=document.createElement('p')
        p3.textContent=`Type: ${element.Type}`
    
        var div=document.createElement('div')
        div.appendChild(img)
        div.appendChild(p1)
        div.appendChild(p2)
        div.appendChild(p3)
                     body.appendChild(div);
                  });
    
    
    
                  } else {
                    console.log(httpRequest.statusText);
                  }
                }
              };
    
    
              httpRequest.onerror = function() {
                console.log(httpRequest.statusText);
              };
    
    
        var searchMovie = function () {
          var input = document.querySelector('input').value;
          
          if (input) {  
    
    
                  httpRequest.open('GET', 'https://www.omdbapi.com/?s=' + input + '&plot=short&apikey=b7da8d63');
                  httpRequest.send(null);
    
        }
        };
    
        searchMovie();
    
        var eve = document.getElementById("myInput");
        
        eve.addEventListener("keyup", function(event) {
        
          if (event.keyCode === 13) {
          searchMovie();
          }
        });;
    .input{
    position: fixed;}
    <input type="text" class="input" id="myInput" name="country" value="time" ><br><br>
    
        <span id="main"></span>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      • 2021-12-27
      相关资源
      最近更新 更多