XHR Example
Grabs weather from yahoo and outputs it.
by Shane Porter
HTML
<table id="weather">
<thead>
<tr>
<th id="header" colspan="2">Conditions</th>
</tr>
</thead>
</table>
CSS
table {
width: 300px;
border-spacing: 0;
border-collapse: collapse;
}
th {
width: 25%;
border-bottom: 1px solid gray;
}
td {
width: 75%;
border-bottom: 1px solid gray;
border-left: 1px solid gray;
padding-left: 5px;
}
JavaScript
var a = prompt("Please specify a city and state/country. e.g. 'Dublin, IE'");
console.log(a);
var b = encodeURIComponent(a);
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22"+b+"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', function (e) {
var tbody, data, output = '';
if (xhr.status == 200) {
//turn the response into a json object
data = JSON.parse(xhr.responseText);
// update the header row
document.getElementById('header').innerHTML = data.query.results.channel.item.title;
// grab just the conditions node
conditions = data.query.results.channel.item.condition;
//format the output in a table body
for (var key in conditions) {
output += '<tr>';
output += '<th>' + key + '</th><td>' + conditions[key] + '</td>';
output += '</tr>';
}
output += '</tbody>';
tbody = document.createElement('tbody');
tbody.innerHTML = output;
document.getElementById('weather').appendChild(tbody);
}
});
xhr.open('GET', url, true);
xhr.send();