我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
当前回答
浏览器(和Dashcode)提供了一个XMLHttpRequest对象,可用于从JavaScript发出HTTP请求:
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
然而,不鼓励同步请求,并将生成如下警告:
注意:从Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27)开始,由于对用户体验的负面影响,主线程上的同步请求已被弃用。
您应该在事件处理程序中发出异步请求并处理响应。
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
其他回答
为了刷新来自joann的最佳答案,这是我的代码:
let httpRequestAsync = (method, url) => {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (xhr.status == 200) {
resolve(xhr.responseText);
}
else {
reject(new Error(xhr.responseText));
}
};
xhr.send();
});
}
在纯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();
});
}
窗口。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 API,使用JavaScript Promises。XMLHttpRequest (XHR)、IFrame对象或动态<script>标记是较旧(且较笨重)的方法。
<script type=“text/javascript”>
// Create request object
var request = new Request('https://example.com/api/...',
{ method: 'POST',
body: {'name': 'Klaus'},
headers: new Headers({ 'Content-Type': 'application/json' })
});
// Now use it!
fetch(request)
.then(resp => {
// handle response
})
.catch(err => {
// handle errors
});
</script>
这里有一个很棒的获取演示和MDN文档
现代、干净、简洁
fetch('https://baconipsum.com/api/?type=1')
让url = 'https://baconipsum.com/api/?type=all-meat¶s=1&start-with-lorem=2'; //只发送GET请求而不等待响应 fetch (url); //使用then来等待结果 获取(url)。然后(r = > r.json()。then(j=> console.log('\nREQUEST 2',j))); //或async/await (异步()= > console.log('\nREQUEST 3', await(await fetch(url)).json()) ) (); 打开Chrome控制台网络选项卡查看请求