Javascript 使用ajax从xml url获取纬度和经度

Javascript 使用ajax从xml url获取纬度和经度,javascript,jquery,xml,ajax,Javascript,Jquery,Xml,Ajax,这是我的jQuery ajax:- function getlg(){ var cntry_code = 'IN'; var reg = 'Rajkot'; var xml; $.ajax( { url: "http://services.gisgraphy.com//geocoding/geocode?address="+reg+"&country="+cntry_code+"", async: false,

这是我的
jQuery ajax
:-

function getlg(){
    var cntry_code = 'IN';
    var reg = 'Rajkot';
    var xml;
    $.ajax(
    {
        url: "http://services.gisgraphy.com//geocoding/geocode?address="+reg+"&country="+cntry_code+"",
        async: false,
        dataType:'xml',
        success: function(data)
        {
            xml=data;
        }
    });
    var lat = $(xml).find('lat:eq(0)').text();
    alert(lat);
    var lng = $(xml).find('lng:eq(0)').text();  
    alert(lng);
}
我正在尝试传递URL城市名称和国家代码,并获取
xml
文件。 试试JSFIDLE:- 从这个
xml
文件中,我尝试获取第一个
lat
lng
元素值

这是

我尝试在ajax url中传递城市名称和国家代码,但不返回纬度和经度值

它如何使用javascript工作


谢谢。

您可以使用
jsonp
,因此您需要在url中包含
format=json

"http://services.gisgraphy.com//geocoding/geocode?address="+reg+"&country="+cntry_code+"&format=json"
以下是工作代码:

$.ajax({
    url: "http://services.gisgraphy.com//geocoding/geocode?address=" + reg + "&country=" + cntry_code + "&format=json",
    async: false,
    dataType: 'jsonp',
    success: function (data) {
           var lat = data.result[0].lat;
           console.log(lat);
           var lng = data.result[0].lng;
           console.log(lng);
       }
});

演示-->

您可以使用
jsonp
,因为您需要在url中包含
format=json

"http://services.gisgraphy.com//geocoding/geocode?address="+reg+"&country="+cntry_code+"&format=json"
以下是工作代码:

$.ajax({
    url: "http://services.gisgraphy.com//geocoding/geocode?address=" + reg + "&country=" + cntry_code + "&format=json",
    async: false,
    dataType: 'jsonp',
    success: function (data) {
           var lat = data.result[0].lat;
           console.log(lat);
           var lng = data.result[0].lng;
           console.log(lng);
       }
});

演示-->

您好,我正在全局尝试lat和lng变量,并尝试此
成功:函数(数据){lat=data.result[0]。lat;console.log(lat);lng=data.result[0]。lng;console.log(lng);});var数据1=lat+“,”+lng;console.log('out'+data1);}
但其返回未定义。之所以不能以这种方式工作,是因为
jsonp
async
不兼容,因此不能使用
async:false
,因为这对jsonp的工作方式没有影响。我尝试全局地处理lat和lng变量,并尝试此
成功:函数(数据){lat=data.result[0]。lat;console.log(lat);lng=data.result[0]。lng;console.log(lng);});var数据1=lat+“,”+lng;console.log('out'+data1);}
但其返回未定义。之所以不能以这种方式工作,是因为
jsonp
async
不兼容,因此不能使用
async:false
,因为这对jsonp的工作方式没有影响