我需要在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;
}
其他回答
在你的小部件的信息。plist文件,不要忘记设置你的AllowNetworkAccess键为true。
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'restUrl', true)
request.onload = function () {
// Begin accessing JSON data here
}
// Send request
request.send()
最好的方法是使用AJAX(您可以在Tizag页面上找到一个简单的教程)。原因是你可能使用的任何其他技术都需要更多的代码,它不能保证在不返工的情况下跨浏览器工作,并且需要你通过在帧内打开隐藏页面传递url解析其数据并关闭它们来使用更多的客户端内存。 AJAX是解决这种情况的方法。这就是我两年的javascript重度开发讲的。
一个复制粘贴的现代版本(使用fetch和箭头函数):
//Option with catch
fetch( textURL )
.then(async r=> console.log(await r.text()))
.catch(e=>console.error('Boo...' + e));
//No fear...
(async () =>
console.log(
(await (await fetch( jsonURL )).json())
)
)();
复制粘贴的经典版本:
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
document.body.className = 'ok';
console.log(this.responseText);
} else if (this.response == null && this.status === 0) {
document.body.className = 'error offline';
console.log("The computer appears to be offline.");
} else {
document.body.className = 'error';
}
}
};
request.open("GET", url, true);
request.send(null);
你可以通过两种方式获得HTTP get请求:
该方法基于xml格式。您必须为请求传递URL。 xmlhttp.open(“获得”、“URL”,真正的); xmlhttp.send (); 它是基于jQuery的。您必须指定要调用的URL和function_name。 $ (btn) .click(函数(){ 美元。Ajax ({url: "demo_test.txt", success: function_name(result) { $ (" # innerdiv ") . html(结果); }}); });