【问题标题】:parse xml using jquery ajax and geolocation使用 jquery ajax 和地理位置解析 xml
【发布时间】:2013-02-27 00:53:47
【问题描述】:

我想使用地理定位来获取我当前的位置并且它可以工作,然后我想解析 latlon 应该是我的位置的 xml。但我的代码似乎有些问题:

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');
    }
});

});

【问题讨论】:

    标签: javascript xml ajax jquery


    【解决方案1】:

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

    将您的 AJAX 调用移至 displayPosition(),看看是否可以为您解决问题。

    【讨论】:

    • 将您的 URL 构建为一个单独的变量,并在您的 AJAX 调用之前将其记录到控制台。是因为displayPosition() 没有得到任何数据,还是因为你的 URL 被破坏了?
    • 抱歉,我不知道如何登录到控制台。你的意思是这样吗? console.log("url: "+ http://**/festivalapi.php? method=getPhotos&amp;returntype=xml&amp;lat=" + mylat + "&amp;lon="+ mylong "); 如果我运行 console.log("url: " + mylat + mylong); 它将正确显示在控制台中。所以 displayPosition() 没有任何问题。此外,网址没有损坏..非常感谢..@hrunting
    • 您能否更具体地说明实际出了什么问题?您的错误处理程序是否被调用?你没有得到你期望的价值吗?您发布的代码不会发送正确的 URL,但现在看来您正在发送正确的 URL 并出现意外行为。什么是意外行为?
    • 很抱歉我没有发送整个 URL,因为它使用了我的 uni 服务器并且运行良好。问题是如果代码是这样的 returntype=xml&amp;lat=" + mylat + "&amp;lon="+ mylong ", 而不是 returntype=xml&amp;lat=54.911859&amp;lon=-1.343404 应用程序完全不能工作,控制台说:Uncaught SyntaxError: Unexpected identifier @hrunting
    • 没关系,我现在看到了。您的 URL 字符串中的 mylong 后面有一个 "
    猜你喜欢
    • 2016-01-17
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    相关资源
    最近更新 更多