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

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

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成功函数中的实际有用代码却没有。

有人可以帮忙吗?

最佳答案

您的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() );
            }
        });

10-07 19:04
查看更多