XHR Example
Grabs weather from yahoo and outputs it.
by phate101101
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 url = "https://query.yahooapis.com/v1/public/yql?q=SELECT+item.condition%2citem.title+FROM+weather.forecast+WHERE+woeid%3d23388266&format=json";
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();