我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
当前回答
现在使用异步js,我们可以使用fetch()方法以更简洁的方式做出承诺。所有现代浏览器都支持异步函数。
async函数funcName(url){ Const response = await fetch(url); Var data = await response.json(); }
其他回答
Ajax
你最好使用Prototype或jQuery这样的库。
// 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()
jQuery:
$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);
你可以通过两种方式获得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(结果); }}); });
如果希望将代码用于Dashboard小部件,并且不希望在创建的每个小部件中都包含JavaScript库,那么可以使用Safari本机支持的对象XMLHttpRequest。
据Andrew Hedges报道,默认情况下,小部件不能访问网络;你需要改变信息中的设置。与小部件关联的Plist。