I’m trying to write a simple AJAX method to get a list of videos from Vimeo without using jQuery. I realize that I must use the JSONP format because it is a cross-domain request. However, the result returned is always 200 OK and it is always empty. Here’s my method:
var httpRequest = new XMLHttpRequest();
httpRequest.open("GET", "http://vimeo.com/api/v2/channel/staffpicks/videos.json?callback=?", true);
httpRequest.send();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 0) {
console.log("0");
}
if (httpRequest.readyState == 1) {
console.log("1");
}
if (httpRequest.readyState == 2) {
console.log("2");
}
if (httpRequest.readyState == 3) {
console.log("3");
}
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
console.log("4");
}
if (httpRequest.readyState == 4 && httpRequest.status == 404) {
console.log("5");
}
};
The console logs 2, but not 0, 1, 3, 4, or 5. It’s always just 2.
By the way, this doesn’t have to be a Vimeo request. The only reason I’m using a Vimeo URL is because I don’t know how else to test an AJAX request than to hit an actual site.
In retrospect, this is a pretty poor question. It’s really two or three questions:
The answers to questions one and two are below, posted by Alexander and Eswar Rajesh Pinapala, respectively. The answer to question three is to request a local JavaScript file.
One thing I struggled with that others might benefit from is that httpRequest.status throws an exception when httpRequest.readyState is 0 or 1. So this doesn’t work:
Here is what worked for me:
The reason for wrapping the constructor, open, and send methods in a try…catch statement is so you can catch any errors that result from a bad filename or something. These will blow up before it ever gets into the onreadystatechange function. The onreadystatechange property is only initialized once the send method has been called.