XHR Example
Grabs weather from yahoo and outputs it.
by Felis Catus
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 = "http1s://query.yahooapis.com/v1/public/yql?q=SELECT%20item.condition%20FROM%20weather.forecast%20WHERE%20location%3D%2297526%22&format=json&callback=";
var xhr = new XMLHttpRequest();
var synccheck;
xhr.onreadystatechange = function (e) {
if (this.readyState === 4 && this.status == 200) {
//turn the response into a json object
data = JSON.parse(xhr.responseText);
//grab just the condition node
conditions = data.query.results.channel.item.condition;
//format the output in a table
var output = '<table><tr><th colspan="2">Grants Pass Weather</th></tr>';
for (var key in conditions) {
output += '<tr>';
output += '<th>' + key + '</th><td>' + conditions[key] + '</td>';
output += '</tr>';
}
output += '<tr><th>check</th><td>'+synccheck+'</td></tr>';
document.body.innerHTML = output + "</table>";
console.log("ready state changed");
}
else
{
console.log(synccheck);
}
}
synccheck = 1;
xhr.open('GET', url, true);
synccheck = 2;
xhr.send();
synccheck = 3;
console.log('finish',synccheck);