[英]Javascript XMLHttpRequest Puzzler: Asynchronous vs. Synchronous
In building a Firefox extension, I have a dialog that calls a Javascript function when the user hits the "OK" button. 在构建Firefox扩展时,我有一个对话框,当用户单击“确定”按钮时,该对话框将调用Javascript函数。 That function looks like this:
该函数如下所示:
var acceptSubscribeHttpReq = null;
function acceptSubscribe(url) {
acceptSubscribeHttpReq = new XMLHttpRequest();
acceptSubscribeHttpReq.onload = httpLoadedSubscribe;
acceptSubscribeHttpReq.onerror = httpErrorSubscribe;
try {
acceptSubscribeHttpReq.open("GET", url, true);
acceptSubscribeHttpReq.send(null);
} catch(e) {
acceptSubscribeHttpReq.abort();
return false;
}
// alert("request.status = "+acceptSubscribeHttpReq.status);
return true;
}
Interestingly, this works fine if I use a synchronous send (by setting the third argument of open to false), or if I uncomment the alert at the end of the function. 有趣的是,如果我使用同步发送(通过将open的第三个参数设置为false),或者在函数末尾取消注释警报,则此方法会很好地工作。 But if I use asynchronous without uncommenting the alert, then this fails silently -- I return from this function as expected, but the onload handler never fires.
但是,如果我在不取消注释注释的情况下使用异步,则此操作将以静默方式失败-我按预期从该函数返回,但是onload处理函数永远不会触发。
This seems to indicate that the XMLHttpRequest object is being destroyed when the function exits. 这似乎表明该函数退出时XMLHttpRequest对象已被破坏。 Is that correct?
那是对的吗? Is that happening because this is being called from a button?
发生这种情况是因为是通过按钮调用的? And if so, what are the possible solutions?
如果是这样,可能的解决方案是什么? If that's not the case, any idea why this would be happening?
如果不是这种情况,为什么会这样呢?
Here is the XUL for the dialog: 这是对话框的XUL:
<dialog id="winMain" title="&settingWindow.title;" style="min-width:400px;"
onload="initSubscribe();" ondialogaccept="return acceptSubscribe();"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
Any and all help appreciated! 任何和所有帮助表示赞赏!
The field status of the request only exists after the request has finished (onload / onerror). 请求的字段状态仅在请求完成后才存在(onload / onerror)。 If you try to access this field before the request has been finalized, you will have an error because such a field does not exists.
如果您在请求完成之前尝试访问此字段,则将出现错误,因为该字段不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.