我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
当前回答
窗口。fetch是使用ES6承诺的XMLHttpRequest的现代替代品。这里有一个很好的解释,但它可以归结为(来自文章):
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(err) {
console.log('Fetch Error :-S', err);
});
自2017年以来,浏览器支持一直很好。IE可能不会得到官方的支持。GitHub有一个可用的polyfill,增加了对一些传统浏览器的支持(特别是2017年3月之前的Safari版本和同期的移动浏览器)。
我想这是否比jQuery或XMLHttpRequest更方便取决于项目的性质。
这里是规范https://fetch.spec.whatwg.org/的链接
编辑:
使用ES7 async/await,这变得很简单(基于这个Gist):
async function fetchAsync (url) {
let response = await fetch(url);
let data = await response.json();
return data;
}
其他回答
窗口。fetch是使用ES6承诺的XMLHttpRequest的现代替代品。这里有一个很好的解释,但它可以归结为(来自文章):
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(err) {
console.log('Fetch Error :-S', err);
});
自2017年以来,浏览器支持一直很好。IE可能不会得到官方的支持。GitHub有一个可用的polyfill,增加了对一些传统浏览器的支持(特别是2017年3月之前的Safari版本和同期的移动浏览器)。
我想这是否比jQuery或XMLHttpRequest更方便取决于项目的性质。
这里是规范https://fetch.spec.whatwg.org/的链接
编辑:
使用ES7 async/await,这变得很简单(基于这个Gist):
async function fetchAsync (url) {
let response = await fetch(url);
let data = await response.json();
return data;
}
jQuery:
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
简单的异步请求:
function get(url, callback) {
var getRequest = new XMLHttpRequest();
getRequest.open("get", url, true);
getRequest.addEventListener("readystatechange", function() {
if (getRequest.readyState === 4 && getRequest.status === 200) {
callback(getRequest.responseText);
}
});
getRequest.send();
}
现在使用异步js,我们可以使用fetch()方法以更简洁的方式做出承诺。所有现代浏览器都支持异步函数。
async函数funcName(url){ Const response = await fetch(url); Var data = await response.json(); }
在纯javascript和返回一个承诺:
httpRequest = (url, method = 'GET') => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = () => {
if (xhr.status === 200) { resolve(xhr.responseText); }
else { reject(new Error(xhr.responseText)); }
};
xhr.send();
});
}