kly*_*aek 4 html javascript http xmlhttprequest
我使用XMLHttpRequest以下方式异步发出http请求:
xhr.open(method, uri, true);
Run Code Online (Sandbox Code Playgroud)
当我发送something:
xhr.send(something)
Run Code Online (Sandbox Code Playgroud)
当服务器关闭时,它会引发以下错误:
net::ERR_CONNECTION_REFUSED
Run Code Online (Sandbox Code Playgroud)
如何捕获并处理此错误?标准try..catch块不起作用,因为请求是异步的.
提前致谢.
使用以下onerror事件XMLHttpRequest:
function aGet(url, cb) {
var x = new XMLHttpRequest();
x.onload = function(e) {
cb(x.responseText)
};
x.onerror= function(e) {
alert("Error fetching " + url);
};
x.open("GET", url, true);
x.send();
}
var dmp = console.log.bind(console); // Dummy callback to dump to console
aGet("/", dmp) // Ok, uses onload to trigger callback
aGet("http://dgfgdf.com/sdfsdf", dmp); // Fails, uses onerror to trigger alert
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11003 次 |
| 最近记录: |