这是您的代码片段的完全等价物,但在 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 这样的库来抽象出这种样板。