我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
我需要在JavaScript中做一个HTTP GET请求。最好的方法是什么?
我需要在Mac OS X的dashcode小部件中做到这一点。
当前回答
上面有很多很好的建议,但不是很可重用,而且经常充满了DOM废话和其他隐藏了简单代码的无用之处。
下面是我们创建的一个可重用且易于使用的Javascript类。目前它只有一个GET方法,但这对我们来说是可行的。添加POST不应该对任何人的技能征税。
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
使用它就像:
var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
// do something with response
});
其他回答
我不熟悉Mac OS的Dashcode小部件,但如果他们让你使用JavaScript库和支持xmlhttprequest,我会使用jQuery,做这样的事情:
var page_content;
$.get( "somepage.php", function(data){
page_content = data;
});
对于那些使用AngularJs的人来说,它是$http.get:
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
如果希望将代码用于Dashboard小部件,并且不希望在创建的每个小部件中都包含JavaScript库,那么可以使用Safari本机支持的对象XMLHttpRequest。
据Andrew Hedges报道,默认情况下,小部件不能访问网络;你需要改变信息中的设置。与小部件关联的Plist。
要做到这一点,建议使用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文档
一种支持旧浏览器的解决方案:
function httpRequest() {
var ajax = null,
response = null,
self = this;
this.method = null;
this.url = null;
this.async = true;
this.data = null;
this.send = function() {
ajax.open(this.method, this.url, this.asnyc);
ajax.send(this.data);
};
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch(e) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP.3.0");
}
catch(error) {
self.fail("not supported");
}
}
}
if(ajax == null) {
return false;
}
ajax.onreadystatechange = function() {
if(this.readyState == 4) {
if(this.status == 200) {
self.success(this.responseText);
}
else {
self.fail(this.status + " - " + this.statusText);
}
}
};
}
这段代码可能有点过分,但绝对是安全的。
用法:
//create request with its porperties
var request = new httpRequest();
request.method = "GET";
request.url = "https://example.com/api?parameter=value";
//create callback for success containing the response
request.success = function(response) {
console.log(response);
};
//and a fail callback containing the error
request.fail = function(error) {
console.log(error);
};
//and finally send it away
request.send();