【问题标题】:How to get whole data out of callback function in javascript如何从javascript中的回调函数中获取全部数据
【发布时间】:2013-12-25 11:53:59
【问题描述】:

我编写了以下函数,该函数从 url 获取 json 数据。

function getWeatherDataForCities(cityArray){
  var arrAllrecords = [];
  var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
  for(var i in cityArray){

    for(var j=1; j<=2; j++){
        var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;

        $.ajax({
            url: jsonurl,
            dataType: "jsonp",
            mimeType: "textPlain",
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            success: function(data){
              arrAllrecords[j]["cityName"] = data.list[0].city.name;
              arrAllrecords[j]["weather"] = data.list[0].weather[0].description;

        } });
        toDaysTimestamp = toDaysTimestamp - (24*60*60);
    }   
  }

  return arrAllrecords;  //returning arrAllrecords
}

$(document ).ready(function() {

  var cityArray = new Array();
  cityArray[0] = "pune";
  var arrAllRecords = getWeatherDataForCities(cityArray);
  //Print All records returned by getWeatherDataForCities(cityArray);
});

我在上面的代码中写了一些 cmets。我调用了getWeatherDataForCitiesfunction,它返回了来自url的所有记录。我在函数中声明了getWeatherDataForCitiesarray。我想将所有返回的记录添加到那个数组。我已经按照上面的方法进行了尝试,但没有任何内容进入array

在控制台中显示 j 和 arrAllrecords 未定义。

如何从回调函数中获取数组中的所有记录?

我们将非常感谢您的回复

【问题讨论】:

    标签: javascript jsonp jquery-callback


    【解决方案1】:

    您的 getWeatherDataForCities 函数不会返回任何内容,因为 ajax 操作是异步的。您需要为此使用回调。

    修改你的函数以接受回调函数:

    function getWeatherDataForCities(cityArray, callback){
        var arrAllrecords = [];
        var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
        for(var i in cityArray){
    
           for(var j=1; j<=2; j++){
               var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
    
                $.ajax({
                    url: jsonurl,
                    dataType: "jsonp",
                    mimeType: "textPlain",
                    crossDomain: true,
                    contentType: "application/json; charset=utf-8",
                    success: function(data){
                    arrAllrecords[j]["cityName"] = data.list[0].city.name;
                    arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
                    // call the callback here
                    callback(arrAllrecords);
                   } 
                });
               toDaysTimestamp = toDaysTimestamp - (24*60*60);
           }   
       }
    }
    

    并像这样使用它:

    $(document ).ready(function() {
      var cityArray = new Array();
      cityArray[0] = "pune";
       getWeatherDataForCities(cityArray, function(arrAllrecords) {
           // Do something with your data
       });
    });
    

    【讨论】:

    • +1 用于回调和异步/同步字。这就是我想要的。谢谢。
    • 我如何从 getWeatherDataForCities 返回 arrAllrecords。因为我希望它用作 api。我的意思是我想调用 getWeatherDataForCities 方法,如 var data = getWeatherDataForCities(cityarry);我希望你能得到我想说的
    • 您可以在原始方法中的 ajax 调用中设置 async: false。但是回调是首选的方法。自 jQuery 1.8 起,不推荐将 async 设置为 false。
    • 感谢@Saravana 你拯救了我的一天
    【解决方案2】:

    您正在尝试使用空数组。获取值时,它总是会返回 undefined。

    var arrAllrecords = [];
    arrAllrecords[2]; //undefined
    arrAllrecords[2]["cityname"];  //undefined
    

    最好使用对象数组。

    我不知道你为什么使用变量 j。下面的代码对我有用。

    var arrAllrecords = [];
    
    function getWeatherDataForCities(cityArray){
    
      var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
      for(var i in cityArray){
    
        var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
            $.ajax({
                url: jsonurl,
                dataType: "jsonp",
                mimeType: "textPlain",
                crossDomain: true,
                contentType: "application/json; charset=utf-8",
                success: function(data){
    
                arrAllrecords.push({
                    "cityName" : data.list[0].city.name,
                    "weather" : data.list[0].weather[0].description
    
                });
                if(arrAllrecords.length === cityArray.length) {
                    callback(arrAllrecords);
                }
            } });
      }
    }
    
    function callback(arrAllrecords) {
        console.log(arrAllrecords);
    }
    
    
            $(document).ready(function() {
    
                var cityArray = new Array();
                cityArray[0] = "pune";
                cityArray[1] = "mumbai";
                cityArray[2] = "delhi";
                getWeatherDataForCities(cityArray);
    
    
            }); 
    

    【讨论】:

    • 你写的正是我想要的。但是你已经删除了一个循环。我想要的。即每天的每条记录。Json 数组看起来像arrAllrecords.push("25-12-2013": { "cityName" : data.list[0].city.name, "weather" : data.list[0].weather[0].description }, "24-12-2013":{ "cityName" : data. list[0].city.name, "weather" : data.list[0].weather[0].description },);.我写的格式可能错了,但我想要这样的东西。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2016-01-16
    • 2018-05-24
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    相关资源
    最近更新 更多