weixin_33709590 2019-09-16 20:56 采纳率: 0%
浏览 65

jQuery多个Ajax请求

I am trying to create an array in JQuery from multiple ajax requests. This is what I have so far

$(document).ready(function() {

var feedResult = [];
var feedCount = [];

var displayResources = $("#display-resources");  


var arayUrlFederalRegister = [
{ source: "FederalRegister:Beef", url : "https://www.federalregister.gov/api/v1/documents.json?fields%5B%5D=abstract&fields%5B%5D=html_url&fields%5B%5D=publication_date&fields%5B%5D=title&per_page=2&order=newest&conditions%5Bterm%5D=beef&callback=foo"},
{ source: "FederalRegister:Safety", url : "https://www.federalregister.gov/api/v1/documents.json?fields%5B%5D=abstract&fields%5B%5D=html_url&fields%5B%5D=publication_date&fields%5B%5D=title&per_page=2&order=newest&conditions%5Bterm%5D=safety&callback=foo"},
{ source: "FederalRegister:Listeria", url : "https://www.federalregister.gov/api/v1/documents.json?fields%5B%5D=abstract&fields%5B%5D=html_url&fields%5B%5D=publication_date&fields%5B%5D=title&per_page=2&order=newest&conditions%5Bterm%5D=listeria&callback=foo"} ] ;

function getFederal( $thisSource, $thisURL) {
$.ajax({      
  async: true,
  type: "GET",
  dataType: 'jsonp',
 url: $thisURL,
  success: function(result) {
    var thisCount = 0;
    for (var i in result.results) {
      thisCount++;
      feedResult.push({URL:result.results[i].html_url, title:result.results[i].title, date:result.results[i].publication_date, summary:result.results[i].abstract });
    }
    feedCount.push({source:$thisSource, count:thisCount});  
  }
}); 
};

function pushAllFeeds() {
   $.each( arayUrlFederalRegister, function( index, value ) {
       getFederal(value.source, value.url );
   });
};

function displayFeeds($feedResult) {
 var output = '<div class="bsr-results well">';
 $.each( $feedResult, function( index, value ) {
      output +=
        '<h3><a href="' +
        value.URL +
        '" target="_blank">' +
        value.title +
        '</a></h3><div><div class="bsr-date">' +
        value.date +
        '</div><p>' +
        value.abstract +
        '</p></div><hr>';
    });
    output += "</div>";
    displayResources.html(output);      
};


$.when(pushAllFeeds()).then(function() {
 console.log(feedResult);
 displayFeeds(feedResult);
});

});

The console is displaying the feedResult array built up correctly (6 objects) but the displayFeeds function is not populating the #display-resources div element with anything so is acting on the initial empty array. Any ideas on how to deliver the argument to displayFeeds() function after all the ajax requests are done and the feedResult array is complete? Thanks.

  • 写回答

0条回答 默认 最新

    报告相同问题?