繁体   English   中英

如何从两个不同的来源提取JSON数据?

[英]How to pull JSON data from two different sources?

我想知道是否有一种方法可以从两个不同的来源提取和使用JSON数据。 当前,代码如下所示:

//JSON1
$.getJSON('url1',function(data){
    $.each(data,function(key,val){
        //code
    });

});

//JSON2
$.getJSON('url2',function(data){
    $.each(data,function(key,val){
        //code
    });

});

当我这样做时,我似乎发现从一个JSON函数创建的变量在另一函数中不可用,这使得它们很难一起使用。 是否有更好的方法将这两个工具一起使用?

此函数将网址数组和回调作为参数:

function getMultiJSON(urlList,callback) {
  var respList = {};
  var doneCount = 0;

  for(var x = 0; x < urlList.length; x++) {
    (function(url){
      $.getJSON(url,function(data){
          respList[url] = data;
          doneCount++;

          if(doneCount === urlList.length) {
            callback(respList);
          }
      });

    })(urlList[x]);
  }
}

您可以这样使用它:

getMultiJSON(['url1','url2'],function(response) {

     // in this case response would have 2 properties,
     //
     // response.url1  data for url1
     // response.url2  data for url2

     // continue logic here
});

您可能要添加超时,因为如果任何URL加载失败,该函数将永远不会调用处理程序

轻松使用开源项目jinqJs( http://www.jinqJs.com

var data1 = jinqJs().from('http://....').select();
var data2 = jinqJs().from('http://....').select();

var result = jinqJs().from(data1, data2).select();

该示例进行同步调用,您可以通过执行以下操作来进行异步调用:

var data1 = null;
jinqJs().from('http://....', function(self){ data1 = self.select(); });

结果将同时包含两个结果。

如果控制端点,则可以使它一次返回所有想要的数据。 然后您的数据将如下所示:

{
    "url1_data": url1_json_data,
    "url2_data": url2_json_data
}

如果仍然有2个端点需要命中,则可以将第一个ajax调用的结果传递给第二个函数(但这会使您的2个ajax调用同步):

function getJson1(){
    $.getJSON('url1',function(data){
        getJson2(data);
    });
}
function getJson2(json1Data){
    $.getJSON('url2',function(data){
        //Do stuff with json1 and json2 data
    });
}
getJson1();

在函数内使用var (或块,使用let )声明的变量在函数(或块)之外不可用。

$.getJSON('url1',function(data){
    $.each(data,function(key,val){
        var only_accessible_here = key;
    });

});

因此,如果希望在声明它们的函数范围之外访问变量,则需要在使用它们的函数之外声明它们。

var combined_stuff = ''

$.getJSON('url1',function(data){
    $.each(data,function(key,val){
        combined_stuff += val;
    });

});

//JSON2
$.getJSON('url2',function(data){
    $.each(data,function(key,val){
         combined_stuff += val;
    });

});

正如Marc B所说的那样,如果getJSON调用之一失败,或者如果两个都失败,则无法知道首先更新JSON1或首先更新JSON2或仅更新一个顺序,无法知道combined_stuff变量的更新顺序。

如果更新顺序很重要,请在要先调用的功能中调用要使用的第二个。

var combined_stuff = ''

$.getJSON('url1',function(data){
    $.each(data,function(key,val){
        combined_stuff += val;

        //JSON2
        $.getJSON('url2',function(data){
            $.each(data,function(key,val){
                 combined_stuff += val;
            });
        });
    });
});

我建议您使用$ .when函数在jquery中可用,以并行执行两个方法,然后执行操作。 请参阅下面的代码片段,

 var json1 = [], json2 = []; $.when(GetJson1(), GetJson2()).always(function () { //this code will execute only after getjson1 and getjson2 methods are run executed if (json1.length > 0) { $.each(json1,function(key,val){ //code }); } if (json2.length > 0) { $.each(json2,function(key,val){ //code }); } }); function GetJson1() { return $.ajax({ url: 'url1', type: 'GET', dataType: 'json', success: function (data, textStatus, xhr) { if (data != null) { json1 = data; } }, error: function (xhr, textStatus, errorThrown) { json1 = [];//just initialize to avoid js error } } function GetJson2() { return $.ajax({ url: 'url2', type: 'GET', dataType: 'json', success: function (data, textStatus, xhr) { if (data != null) { json2 = data; } }, error: function (xhr, textStatus, errorThrown) { json2 = [];//just initialize to avoid js error } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

每个AJAX调用返回的数据都无法在其自己的回调函数之外使用。 我敢肯定还有更优雅的(复杂的)解决方案,但是有两个简单的Occamic解决方案包括全局变量,或将接收到的数据存储在隐藏的输入元素中。

在每个回调函数中,只需循环直到出现另一个调用的数据:

function getJson1(){
    $.getJSON('url1',function(data){
        var d2 = '';
        $('#hidden1').val(data);
        while ( d2 == '' ){
            //you should use a time delay here
            d2 = $('#hidden2').val();
        }
        getJson2();
    });
}
function getJson2(){
    $.getJSON('url2',function(d2){
        var d1 = '';
        $('#hidden2').val(d2);
        while ( d1 == '' ){
            //you should use a time delay here
            d1 = $('#hidden1').val();
        }
        //Do stuff with json1 and json2 data
    });
}
getJson1();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM