我有一個劇本,我想從一個端點獲取一些JSON數據,但我得到一個錯誤,這是我的腳本:E6 Ajax請求不工作
function httpGet(url) {
return new Promise(
function (resolve, reject) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.status === 200) {
// Success
resolve(this.response);
} else {
// Something went wrong (404 etc.)
reject(new Error(this.statusText));
}
}
request.onerror = function() {
reject(new Error(
'XMLHttpRequest Error: '+this.statusText));
};
request.open('GET', url);
request.send();
});
}
var url = 'https://api.jsonPlaceholder.com';
httpGet(url)
.then(JSON.parse)
.then((r) => {
console.log(r);
}).catch(function(error) {
console.log(error);
});
然後,在控制檯它拋出一個錯誤:
Error at XMLHttpRequest.request.onreadystatechange (app.js:11) at app.js:18 at Promise() at httpGet (app.js:2) at app.js:25
只是好奇...爲什麼不使用['Fetch API'](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)? – Andreas
@Andreas:可能想要支持IE? –
除了api url以外,似乎對我來說運行良好。你使用的是什麼瀏覽器? – epascarello