我正在尝试编写一个简单的 AJAX 方法来从 Vimeo 获取视频列表,而不使用 jQuery。我意识到我必须使用JSONP格式,因为它是跨域请求。但返回的结果始终是200 OK,并且始终为空。这是我的方法:
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");
}
};
控制台记录 2,但不是 0、1、3、4 或 5。它始终只是 2。
顺便说一句,这不一定是 Vimeo 请求。我使用 Vimeo URL 的唯一原因是我不知道除了访问实际网站之外还能如何测试 AJAX 请求。
最佳答案
您需要了解这些数字的含义。
readyState 属性指示请求的当前状态。它返回一个 4 字节整数。
此属性是只读的,具有以下定义值
UNINITIALIZED(0)
The object has been created, but has not been initialized (the open method has not been called).
LOADING(1)
The object has been created but the send method has not been called.
LOADED(2)
The send method has been called and the status and headers are available, but the response is not.
INTERACTIVE(3)
some data has been received. You can get the partial results using the responseBody and the responseText properties.
COMPLETED(4)
All the data has been received, and is available.
尝试
httpRequest.onreadystatechange = function () {
alert(httpRequest.readyState + httpRequest.status);
};
状态:
200 状态正常 400 HTTP 错误 400 错误请求
然后决定您从服务器接收的内容。
关于javascript - 使用 AJAX(无需 jQuery)从 Vimeo channel 获取视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11211642/