gpt4 book ai didi

javascript - 处理 XMLHttpRequest 异常

转载 作者:行者123 更新时间:2023-11-28 01:40:01 25 4
gpt4 key购买 nike

鉴于此代码

var xhr = new XMLHttpRequest();
xhr.open('get', 'http://example.com', false);
alert(0);
xhr.send();
alert(1);

如果http://example.com是跨域URL,它将导致xhr.send()出现异常。那么永远不会达到alert(1)

我怎样才能这样写,即使它是一个“坏”URL,它也能一直走到最后?

最佳答案

MDN try/catch

var xhr = new XMLHttpRequest();
xhr.open('get', 'http://example.com', false);
alert(0);
try {
xhr.send();
} catch (e) {
console.log(e);
}
alert(1);

关于javascript - 处理 XMLHttpRequest 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21032513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com