javascript - 如何避免为两个单独的数据源嵌套 getJSON?

标签 javascript jquery

现在我有以下内容:

$.getJSON("firsturl", function(source1) {
   $.getJSON("secondurl", function(source2) {
      // I have source 1 and source 2 data here!
   }
}

有什么更好的方法可以从两个来源获取数据......并在不嵌套所有这些 $.getJSON 调用的情况下对它们进行处理?

最佳答案

您可以使用 $.when

$.when($.getJSON("/firsturl"), $.getJSON("secondurl")).done(function(result1, result2){
  /* result1 and result2 are arguments resolved for the
      page1 and page2 ajax requests, respectively. 
      each argument is an array with the following 
      structure: [ data, statusText, jqXHR ] */
});

关于javascript - 如何避免为两个单独的数据源嵌套 getJSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17280952/

相关文章:

javascript - 尝试拉取 xml/json

javascript - 用于选择带有类的输入字段的 jQuery 选择器

javascript - 通过ajax api调用从多个对象获取数据

javascript - 清除旧的 Meteor 订阅数据

javascript - Mapbox.js - 单击列表中的项目并平移到标记并显示弹出窗口

javascript - 为什么javascript中的回调不起作用?

javascript - 有没有办法在两个不同的页面之间制作动画滚动过渡?

javascript - 使用 Instagram feed 填充网页并调整大小

javascript - 土耳其字符串的子字符串

javascript - 如何将此类对象的此类数组传递给 JS?