2011-09-03 128 views
0

我成功地从一些XML创建对象。然后,我试图将每个新对象放入一个数组的新索引中,该索引最终将包含所有对象。javascript数组对象

但是,数组不断返回为空。我的代码如下:

var $locations = []; 
      /*$obj = {}; 
      $obj['test'] = 'working'; 
      $locations.push($obj);*/ 

      $.ajax({ 
       type:  "POST", 
       url:  "/locations/845/data.xml", 
       dataType: "xml", 
       success: function($xml){ 

        $($xml).find('node').each(
         function(){ 
          $location = {}; 
          //alert($(this).attr('Latitude')); 
          $location['latitude'] = $(this).attr('Latitude'); 
          $location['longitude'] = $(this).attr('Longitude'); 
          $location['city']  = $(this).attr('City'); 
          $location['street']  = $(this).attr('Street'); 

          //alert($location.toSource()); 
          //alert($location['latitude']); 
          $locations.push($location); 
         } 
        ); 
       } 
      }); 
      alert($locations.toSource()); 

创建并插入$ locations数组的注释对象是一个测试,它的工作原理。但是,ajax成功函数中的实际有用代码却没有。

任何人都可以帮忙吗?

+0

阿贾克斯是异步的。在Ajax调用完成之前显示您的警报。 – JJJ

+0

你为什么喜欢把'$'放在JS变量前? – Cipi

+0

嗨Cipi,我只使用$在JS变量的前面,因为我习惯这样做从编写PHP代码。无论您是否使用$ – sisko

回答

4

您的ajax调用是异步的。当你调用它时,它只是开始执行它,其余的代码继续运行。当警报触发时,ajax尚未完成,直到成功处理函数被调用才会完成。只有你能够知道ajax调用完成的地方在于成功处理程序本身。实际上,你想要处理的返回的ajax数据应该从成功处理程序启动,而不是从调用ajax调用之后执行的代码中启动。

如果招行:

alert($locations.toSource()); 

的成功处理函数结束,然后你会看到你的数据。只有这样才能实际完成ajax调用。

试试这样说:

 var $locations = []; 
     /*$obj = {}; 
     $obj['test'] = 'working'; 
     $locations.push($obj);*/ 

     $.ajax({ 
      type:  "POST", 
      url:  "/locations/845/data.xml", 
      dataType: "xml", 
      success: function($xml){ 

       $($xml).find('node').each(
        function(){ 
         $location = {}; 
         //alert($(this).attr('Latitude')); 
         $location['latitude'] = $(this).attr('Latitude'); 
         $location['longitude'] = $(this).attr('Longitude'); 
         $location['city']  = $(this).attr('City'); 
         $location['street']  = $(this).attr('Street'); 

         //alert($location.toSource()); 
         //alert($location['latitude']); 
         $locations.push($location); 
        } 
       ); 
       alert($locations.toSource()); 
      } 
     }); 
+0

谢谢!我踢我自己b'cus我应该知道这一点。感谢您的协助。 – sisko