Javascript - 如何访问成功块之外的对象

时间:2015-01-15 15:23:58

标签: javascript arrays ajax object

我需要在AJAX修改后访问一个对象但是当我尝试打印它时会显示一个空值

我该如何解决这个问题?

 $(document).ready(function(){
   var arrayLength = whatever...;
   var myArray = [];

   for (var i = 0; i < arrayLength; i++) {

       $.ajax({
           myArray: myArray,
           type: 'GET',
           dataType: 'jsonp',
           data: {},
           url: "https://api....",
           error: function (jqXHR, textStatus, errorThrown) {
               console.log(jqXHR)
           },
           success: function (response) {
               var name = response.data.name;
               var url = response.data.url;
               for(var x = 0; x < 5; x++) {
                   var pin = {name: name, url:url};
                   myArray.push(pin);
               }
           },
           async: false
       });
   }

   // I want to print myArray here
});

1 个答案:

答案 0 :(得分:0)

 $(document).ready(function(){
   var arrayLength = whatever...;
   var myArray = [];

   for (var i = 0; i < arrayLength; i++) {

       $.ajax({
           //myArray: myArray,
           type: 'GET',
           dataType: 'jsonp',
           data: {},
           url: "https://api....",
           error: function (jqXHR, textStatus, errorThrown) {
               console.log(jqXHR)
           },
           success: function (response) {
               var name = response.data.name;
               var url = response.data.url;
               for(var x = 0; x < 5; x++) {
                   var pin = {name: name, url:url};
                   //allPins.push(pin);
                   myArray.push(pin);
               }
           },
           async: false
       });
   }

   // I want to print myArray here
});