2014-02-19 50 views
0

我所试图做的事:检索XML数据,使用网页

  • 获取基于位置的关闭IP(完成)
  • 使用的城市和国家代码使用openweather的API(完成)
  • 将XML读入我的网页,以便我可以显示“温度”字段。

这是我在网页中使用XML的第一次冒险,我已经尝试了3天,但没有成功。我搜索了谷歌和stackoverflow,并尝试了很多东西,包括SimpleXMLElement,没有运气。

我目前在我的页面上只是一个生成的链接到您的位置的XML表。

<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script> 
<script language="JavaScript"> 
    var country = geoip_country_code(); 
    var city = geoip_city(); 
    document.write('<a href="http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=xml&units=metric">Link text</a>'); 
</script> 

我怎样才能显示我的网页上的必填字段的文本?

在此先感谢! :)

回答

1

可能更容易改变API调用返回JSON,在这种情况下,你可以再使用此代码,临时工都存储在temp,temp_min和temp_max。

var country = geoip_country_code(); 
var city = geoip_city(); 

$.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=json&units=metric', function(json) { 
    var temp = json.main.temp; 
    var temp_min = json.main.temp_min; 
    var temp_max = json.main.temp_max; 

    document.write('Temp: ' + temp + '<br>'); 
    document.write('Temp Min: ' + temp_min + '<br>'); 
    document.write('Temp Max: ' + temp_max + '<br>'); 
}); 
+0

这是容易得多!谢谢你,它完美的工作! –

+0

只是一个简单的问题,当我在页面中有该代码时,它将用白色背景替换所有内容,并仅替换这些值。我尝试将“document.write”行放在我的页面中,但没有任何内容出现。 –

0

你可以使用JavaScript库的XML转换为JavaScript对象 - 一个这样的库称为xml2json,它可以作为一个jQuery插件:http://www.fyneworks.com/jquery/xml-to-json/

然后,你可以简单地做:

var xmlObject; 

$.ajax({ 
    url: url_of_xml, 
    success: function(data) { 
     xmlObject = $.xml2json(data); 
    } 
}); 

然后你只需要将数据放在你的页面上即可。在我的例子中的对象是伪造的,但它给你的想法:

// put this line in the success callback of your ajax call 
// after you create the xmlObject 
$('#temp').html(xmlObject.weather.temp); 
0

要显示temperature你得到的XML,并读取三个温度的一个从XML属性返回:

$.get("http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=xml&units=metric", function(xml) { 
avg = $(xml).find("temperature").attr("value")); 
max = $(xml).find("temperature").attr("max")); 
min = $(xml).find("temperature").attr("min")); 

(使用JQuery)