从XML源创建对象的JavaScript数组

Creating an JavaScript array of objects from an XML source

本文关键字:JavaScript 数组 创建对象 XML      更新时间:2023-09-26

我成功地从一些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() );
            }
        });