使用 deferred 强制一个调用在刷新前完成
Using deferred to force one call finishes before refresh
我的 JavaScript 代码中有一个 ajax 调用,它在服务器端代码的响应中接收 GUID。在成功方法上,它使用该 GUID 调用 iframe,然后在该调用完成后,它应该刷新页面。
我在 fiddler 中看到的是 iframe 会话正在中止。我唯一的猜测是它在强制刷新时被浏览器中止:如果我删除刷新部分,iframe 会话发送请求并成功接收响应。
如何在iframe完成后刷新页面?有人建议我使用promise,但我在[=28]中尝试了$.Deferred()
=] 仍然没有成功。我想我没有正确使用 $.Deferred()
方法。
注意:如果我设置 ajax 以同步方式调用,它会起作用,但我希望找到更好的解决方案。
这是我的代码:
foo() {
this.$link.click((e) => {
e.preventDefault();
$.ajax({
url: "/serverEndpoint",
type: "POST",
success: (id) => {
this.iframeCall(id);
window.location.href = window.location.origin;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
});
}
iframeCall(id) {
var iframe = document.createElement('IFRAME');
iframe.setAttribute("src", someUrl+id);
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
当 iframe
元素的 load
事件被分派时,您可以 return 来自 iframeCall()
的 jQuery 延迟对象,然后执行任务
iframeCall(id) {
return new $.Deferred(function(dfd) {
var iframe = document.createElement('IFRAME');
iframe.onload = dfd.resolve;
iframe.setAttribute("src", someUrl+id);
iframe.style.display = 'none';
document.body.appendChild(iframe);
})
}
this.iframeCall(id).then(function() {
window.location.href = window.location.origin;
})
我的 JavaScript 代码中有一个 ajax 调用,它在服务器端代码的响应中接收 GUID。在成功方法上,它使用该 GUID 调用 iframe,然后在该调用完成后,它应该刷新页面。
我在 fiddler 中看到的是 iframe 会话正在中止。我唯一的猜测是它在强制刷新时被浏览器中止:如果我删除刷新部分,iframe 会话发送请求并成功接收响应。
如何在iframe完成后刷新页面?有人建议我使用promise,但我在[=28]中尝试了$.Deferred()
=] 仍然没有成功。我想我没有正确使用 $.Deferred()
方法。
注意:如果我设置 ajax 以同步方式调用,它会起作用,但我希望找到更好的解决方案。
这是我的代码:
foo() {
this.$link.click((e) => {
e.preventDefault();
$.ajax({
url: "/serverEndpoint",
type: "POST",
success: (id) => {
this.iframeCall(id);
window.location.href = window.location.origin;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
});
}
iframeCall(id) {
var iframe = document.createElement('IFRAME');
iframe.setAttribute("src", someUrl+id);
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
当 iframe
元素的 load
事件被分派时,您可以 return 来自 iframeCall()
的 jQuery 延迟对象,然后执行任务
iframeCall(id) {
return new $.Deferred(function(dfd) {
var iframe = document.createElement('IFRAME');
iframe.onload = dfd.resolve;
iframe.setAttribute("src", someUrl+id);
iframe.style.display = 'none';
document.body.appendChild(iframe);
})
}
this.iframeCall(id).then(function() {
window.location.href = window.location.origin;
})