使用jquery ajax和geolocation解析xml

时间:2013-02-27 00:53:47

标签: javascript xml ajax jquery

我想使用地理位置获取我当前的位置并且它有效,然后我想解析xml,其中latlon应该是我的位置。但是我的代码似乎有些不对劲:

url: "http://**/festivalapi.php? method=getPhotos&returntype=xml&lat=" + mylat + "&lon="+ mylong ",

但如果我直接使用lat和lon就可以了。像这样:

url: http://**/festivalapi.php? method=getPhotos&returntype=xml&lat=54.911859&lon=-1.343404` 

所以我觉得这里一定有一些语法错误..

这是整个jquery:

$(document).ready(function () {

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayPosition, errorFunction, { enableHighAccuracy: true, maximumAge: 30000, timeout: 27000 });
} else {
    alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}

function displayPosition(pos) {
    var mylat = pos.coords.latitude;
    var mylong = pos.coords.longitude;
    var thediv = document.getElementById('locationinfo');
    thediv.innerHTML = '<p>Your latitide is :' +
        mylat + ' and your longitude is ' + mylong + '</p>';
}

// Error callback function
function errorFunction(pos) {
    alert('Error!');
}



$.ajax({
    type: "GET",
    url: "http://**/festivalapi.php? method=getPhotos&returntype=xml&lat=" + mylat + "&lon="+ mylong ",
    dataType: "xml",
    success: function (xml) {
        $(xml).find('photo').each(function () {
            var name = $(this).find('name').text();
            var url = $(this).find('url').text();

            $('<li></li>').append("<img src='" + url + "'/>").appendTo('#photos');


        });
    },
    error: function () {
        alert('Sorry, an error occured loading the XML file');
    }
});

});

1 个答案:

答案 0 :(得分:1)

您的mylatmylong变量在var函数中使用displayPosition()声明,但您在AJAX调用中的该函数之外使用它们。它们没有设置在那一点,所以你没有将它们传递给你的AJAX调用。

将您的AJAX通话移至displayPosition()并查看是否可以为您修复此问题。