简体   繁体   中英

Parsing from an XML file

How can I parse lat and long value in jQuery from a php file that outputs this:

<gps>
    <loc lat="42.6438" lon="21.9275" alt="29.7" spd="0" dir="342" cep="203.1" upd="2013-03-09 02:10:31"/>
</gps>

UPDATE! This is my full code in head.php

        $.ajax({
            type: "GET",
            url: "gps-tracking/track.xml",
            dataType:'data',
            complete: function(data){
                    var loc = $("loc");
                    var lat = loc.attr("lat");
                    var lon = loc.attr("lon");
                    console.log(data);
                    console.log(lat);
            }
        });

console.log(data); outputs this:

Object { readyState= 4 , responseXML=document, responseText= "<gps><loc lat="40.6438"...03-09 02:10:31"/></gps>" , more...}

console.log(lat); outputs: undefined!

Actually your code:

complete: function(data){
                    var loc = $("loc");
                    var lat = loc.attr("lat");
                    var lon = loc.attr("lon");
                    alert (lat);
            }

Tries to store a Dom element "loc" into the var loc. First of all you should try to use the data of your complete function, because there your php values are stored.

Then try to create a DOM element like $(data).children('loc').attr('lat');

Small demo fiddle: http://jsfiddle.net/P6JVw/

And here the code you should use:

complete: function(data){
                        var xmlObj = $(data.responseText).children('loc');
                        var loc = xmlObj.attr('loc');
                        var lat = xmlObj.attr('lat');
                        var lon = xmlObj.attr('lon');;
                        alert (lat);
                }

Pretty straightforward. Just call attr()

var loc = $("loc");
var lat = loc.attr("lat");
var lon = loc.attr("lon");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM