如何将我的ajax数据附加到已创建的多个div中?

时间:2017-06-27 04:54:49

标签: javascript jquery json ajax

我正在创建一个使用新闻API的应用,并且我试图将我在已创建的Bootstrap列中返回的数据附加到其中。我不确定如何解决这个问题。我想显示图像,标题和说明。不确定是否更容易划伤HTML并使用If语句和遍历每行的for循环动态创建行以显示所需的行和图像数量?如果有人能指出我正确的方向,我将非常感激!



window.onload = function() {

  API_Call.displayTenArticles();

};

var API_Call = {

  generateRandomSource: function() {

    // Array to store all external news sources from news API
    var allSources = ["abc-news-au", "al-jazeera-english", "bbc-news", "bloomberg", "cnbc", "cnn", "google-news", "breitbart-news", "daily-mail", "reuters", "the-guardian-uk", "the-new-york-times", "the-wall-street-journal", "time", "the-washington-post"];
    // Var to store randomly generated number based off of length of allSources API
    var randomSource = Math.floor(Math.random() * allSources.length);
    // Selected newsource generated on onload
    var selectedSource = allSources[randomSource];
    // Function to select random news source
    // Function to generate 10 images to DOM

    return selectedSource;

  },

  displayTenArticles: function() {

    selectedSource = API_Call.generateRandomSource();

    // API_Call.NYT_API_Call(selectedSource);

    API_Call.NEWS_API_Call(selectedSource);

  },

  parse_Ajax_JSON: function(response) { // Variable to store number of results

    var numberResults = 6;
    // Variable to hold data returned from API
    var results = response.articles;
    console.log(results);
    // Empty display div whenever new high level object is selected
    $("#display-articles").empty();
    // forLoop to iterate through functions 10 times
    for (var i = 0; i < numberResults; i++) {
      // Create div to store generated news articles
      var displayedArticles = $("");
      // Grab title from API
      var articleTitle = results[i].title;
      console.log(articleTitle);
      // Grab description from API
      var descriptionTitle = results[i].description;
      console.log(descriptionTitle);

      //IMAGE Display

      var image = results[i].urlToImage;
      console.log(image);

      // Saving the image_original_url property
      // var imageDiv = $("<div>");
      // var displayedArticles = $("<div>");
      // Creating and storing an image tag
      var articleImage = $("<img>");
      articleImage.attr("src", image);
      // articleImage.attr("class", "gif");    
      displayedArticles.append(articleImage);

      // $("#display-articles").prepend(imageDiv);

      //URL Display
      var articleURL = results[i].url;
      var articleLink = $("<a>");
      articleLink.attr('href', articleURL);
      console.log(articleURL);
      var pThree = articleLink.html(articleURL);


      // Paragraph to store article title
      var pOne = $("<p>").text("Article Title: " + articleTitle);
      // Paragraph to store description of article
      var pTwo = $("<p>").text("Article Descriptoin" + descriptionTitle);
      // Append to displayedArticles div
      // descriptionTitle.append(pTwo);
      displayedArticles.append(pOne);
      displayedArticles.append(pTwo);
      displayedArticles.append(pThree);
      // Append to display-articles div
      $("#display-articles").append(displayedArticles);
      // $("#display-articles").append(descriptionTitle);
    }

  },

  NEWS_API_Call: function() {

    var article = $(this).attr("data-name");
    var queryURL = "https://newsapi.org/v1/articles?source=" + selectedSource + "&sortBy=top&apiKey=01aed6729dc84b87b67d8eca2e2a711b"
    // ajax call to news API
    $.ajax({
      url: queryURL,
      method: 'GET',
    }).done(function(response) {
      console.log(response);

      API_Call.parse_Ajax_JSON(response);

    });

  },

  Blog_API_Call: function(selectedSource) {

    // var article = $(this).attr("data-name");
    /*
      var queryURL = "https://www.googleapis.com/blogger/v3/blogs/blogId/posts/search?q=query" +  selectedSource;
      // ajax call to news API
      $.ajax({
        url:queryURL,
        method: 'GET',
      }).done(function handleResponse(selectedSource) {
        console.log(response);
        document.getElementById("content").innerHTML += "<h1>" + response.title + "</h1>" + response.content;
      }
      
      });
            
       */


  },

};

$("#category-switch").click(function() {
  $('.flip').find(".card").toggleClass("flipped");
  $('.articles').hide();
  $('.blogs').show();
  return false;
});
&#13;
/*Basic Setup*/

* {
  padding: 0;
  margin: 0;
}

body {
  width: 100%;
  padding: 0;
  margin: 0;
  background: #fff;
}

.row {
  padding-top: 10px;
}

.titleChange {
  display: none;
}

footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #efefef;
  text-align: center;
  margin-top: 20px;
}

.blogs {
  display: none;
}

.os-animation {
  opacity: 1!important;
}


/*----------Nav Bar, Links, Sign-Up DropDown-----------*/

#logo {
  max-height: 50px;
  padding-bottom: 5px;
}

.navbar {
  border: none;
  border-radius: none;
  background: #262626;
  box-shadow: 1px 3px #000;
  border-radius: 0px;
}

.navbar-logo {
  width: 100%;
  text-align: center;
}


/*----------Category Switch animation-----------*/

.flip {
  -webkit-perspective: 800;
  -ms-perspective: 800;
  -moz-perspective: 800;
  -o-perspective: 800;
  width: 100%;
  height: 200px;
  position: relative;
}

.flip .card.flipped {
  transform: rotatey(-180deg);
  -ms-transform: rotatey(-180deg);
  /* IE 9 */
  -moz-transform: rotatey(-180deg);
  /* Firefox */
  -webkit-transform: rotatey(-180deg);
  /* Safari and Chrome */
  -o-transform: rotatey(-180deg);
  /* Opera */
}

.flip .card {
  width: 100%;
  height: 100%;
  -webkit-transform-style: preserve-3d;
  -webkit-transition: 0.5s;
  -moz-transform-style: preserve-3d;
  -moz-transition: 0.5s;
  -ms-transform-style: preserve-3d;
  -ms-transition: 0.5s;
  -o-transform-style: preserve-3d;
  -o-transition: 0.5s;
  transform-style: preserve-3d;
  transition: 0.5s;
}

.flip .card .face {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 2;
  font-family: Georgia;
  font-size: 3em;
  text-align: center;
  line-height: 200px;
  backface-visibility: hidden;
  /* W3C */
  -webkit-backface-visibility: hidden;
  /* Safari & Chrome */
  -moz-backface-visibility: hidden;
  /* Firefox */
  -ms-backface-visibility: hidden;
  /* Internet Explorer */
  -o-backface-visibility: hidden;
  /* Opera */
}

.flip .card .front {
  position: absolute;
  z-index: 1;
  background: black;
  color: white;
  cursor: pointer;
}

.flip .card .back {
  background: blue;
  background: white;
  color: black;
  cursor: pointer;
  transform: rotatey(-180deg);
  -ms-transform: rotatey(-180deg);
  /* IE 9 */
  -moz-transform: rotatey(-180deg);
  /* Firefox */
  -webkit-transform: rotatey(-180deg);
  /* Safari and Chrome */
  -o-transform: rotatey(-180deg);
  /* Opera */
}


/*--------------Article Page ---------------*/

#display-articles {
  text-align: center;
  width: 400px;
  height: auto;
}
&#13;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>SorceLess Home</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="./assets/css/style.css">
  <link href="./assets/css/animate.css" type="text/css" rel="stylesheet" />
  <link rel="stylesheet" type="text/css" href="./assets/css/waypoints.css">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
</head>

<body>

  <header class="text-center">
    <nav class="navbar os-animation" data-os-animation="bounceInDown" data-os-animation-delay=".1s" role="navigation">
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-logo">
          <img id="logo" class="img-responsive" src="./assets/img/sourceLesslogo.png">
        </div>
      </div>
      <!-- /.container-fluid -->
    </nav>
    <div class="row text-center os-animation" data-os-animation="bounceInDown" data-os-animation-delay=".3s">
      <div class="col-lg-12">
        <h1 class="articles">Articles</h1>
        <h1 class="blogs">Blogs</h1>
      </div>
    </div>
  </header>
  <div class="container text-center">
    <section id="categories text-center">
      <div class="row os-animation card" onclick="flip()" data-os-animation="fadeInRight" data-os-animation-delay=".3s">
        <div class="col-sm-4">
          <div class="flip">
            <div class="card">
              <div class="face front">
                <p id="title">Title</p>
                <div id="categories"></div>
              </div>
              <div class="face back">
                <p id="title">Title</p>
                <div id="category"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-sm-4">
          <div class="flip">
            <div class="card">
              <div class="face front">
                <p id="title">Title</p>
                <div id="display-articles"></div>
                <p id="description"></p>
              </div>
              <div class="face back">
                <p id="title">Title</p>
                <div id="category"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-sm-4">
          <div class="flip">
            <div class="card">
              <div class="face front">
                <p id="title">Title</p>
                <div id="display-articles"></div>
              </div>
              <div class="face back">
                <p id="title">Title</p>
                <div id="category"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="row os-animation card" onclick="flip()" data-os-animation="fadeInRight" data-os-animation-delay=".3s">
        <div class="col-sm-4">
          <div class="flip">
            <div class="card">
              <div class="face front">
                <p id="title">Title</p>
                <div id="category"></div>
              </div>
              <div class="face back">
                <p id="title">Title</p>
                <div id="category"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-sm-4">
          <div class="flip">
            <div class="card">
              <div class="face front">
                <p id="title">Title</p>
                <div id="category"></div>
              </div>
              <div class="face back">
                <p id="title">Title</p>
                <div id="category"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-sm-4">
          <div class="flip">
            <div class="card">
              <div class="face front">
                <p id="title">Title</p>
                <div id="category"></div>
              </div>
              <div class="face back">
                <p id="title">Title</p>
                <div id="category"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
    <div class="row text-center">
      <div class="col-md-12">
        <button class="btn btn-primary os-animation" data-os-animation="bounceInUp" data-os-animation-delay=".3s" id="category-switch">Click to change sources</button>
      </div>
    </div>
    <!--<footer>
		<div class="row text-center">
			<div class="col-lg-12">
				<p>@SourceLess 2017</p>
			</div>
		</div>
</footer>-->
  </div>
  <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script type="text/javascript" src=./assets/js/jquery.waypoints.min.js></script>
  <script type="text/javascript" src=./assets/js/waypoints.js></script>
  <script type="text/javascript" src="./assets/js/app.js"></script>
</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:-1)

为什么不使用把手或小胡子进行模板化?

这将是一件轻松而又好的事情,因为它可以使您的代码保持清洁和可读性。

如果您需要任何帮助,请与我联系。