是否有一个相当于在JavaScript中的Apache HTTP客户端? [英] Is there an equivalent to the Apache HTTP Client in JavaScript?
问题描述
我是一个新的程序员,其主要背景是在Java中。我试图在故障处理中的Javascript程序编写,因为我会在Java中。在java中我使用Apache HTTP客户端都创建客户端,并调用HTTPGET请求。
I am a new programmer whose primary background is in Java. I am attempting to write in fault handling to a program in Javascript as I would in Java. In java I use the Apache HTTP client to both create the client and call the Httpget request.
HttpClient cli = new DefaultHttpClient();
cli.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
HttpResponse resp = null;
for (int i = 0 ; i < 5 ; i++) {
try {
resp = cli.execute(new HttpGet("http://example.org/products"));
}
catch{//code}
}
我不确定如何在JavaScript环境模仿这种行为。有没有人有洞察力或知识到这个领域?
I am unsure how to emulate this behavior in a javascript environment. Does anyone have insight or knowledge into this field?
推荐答案
下面是你的code段的完全等效的,但在JavaScript中!
Here's the exact equivalent of your code snippet, but in JavaScript!
var cli;
var callback = function(resp) {
// due to the asynchronous nature of XMLHttpRequest, you'll need to put all logic that uses the response in a callback function.
// code below using responseText
console.log(resp);
};
var timeout = 5000;
var handler = function() {
var errorSeries;
if (this.readyState === 4) { // indicates complete
errorSeries = parseInt(this.status.toString().charAt(0)); // will be "2" or "3" for 200 or 300 series responses
if (errorSeries === 2 || errorSeries === 3) {
callback.call(this, this.responseText);
} else {
// handle http error here
}
}
}
for (var i = 0 ; i < 5 ; i++) {
cli = new XMLHttpRequest(); // ActiveXObject('Microsoft.XMLHTTP') in IE8 and below
cli.timeout = timeout;
cli.onreadystatechange = handler;
try {
cli.open('GET','http://example.org/products');
cli.send();
}
catch(e) {
}
如果上述看起来罗嗦,那是因为它是。其他评论者转向你的权利:考虑使用像jQuery库抽象掉这种样板
If the above looks wordy, that's because it is. Other commenters have steered you right: look into using a library like jQuery to abstract away this kind of boilerplate.
这篇关于是否有一个相当于在JavaScript中的Apache HTTP客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!