如何避免为两个独立的数据源嵌套getJSON

How to avoid nesting getJSON for two separate data sources?

本文关键字:独立 数据源 嵌套 getJSON 两个 何避免      更新时间:2023-09-26

现在我有以下内容:

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

从两个来源获取数据的更好方法是什么。。并且在不嵌套所有这些$.getJSON调用的情况下对它们两者都执行某些操作?

时可以使用$

$.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 ] */
});

将jQuery Deferred对象与$.when:一起使用

var first = $.getJSON("firstUrl");
var second = $.getJSON("secondUrl");
$.when(first, second).done(function(firstResult, secondResult) {
  // do stuff;
});