Javascript 在单击事件期间 window.open 弹出窗口被阻止
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6628949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
window.open popup getting blocked during click event
提问by Shpigford
What I ultimately need to do is run an $.ajax()
call and then after that is run, open a new window.
我最终需要做的是运行一个$.ajax()
调用,然后在运行之后打开一个新窗口。
A use clicks on a "Preview" button that saves their current form then opens a new window that shows a preview of the item with the data that was just saved.
用户单击保存当前表单的“预览”按钮,然后打开一个新窗口,该窗口显示带有刚刚保存的数据的项目的预览。
But as-is, the window.open
function gets blocked by popup blockers.
但按原样,该window.open
功能会被弹出窗口阻止程序阻止。
Here's the basic parts of my code:
这是我的代码的基本部分:
HTML:
HTML:
<a href="/surveys/185/preview" class="preview" target="_blank">Preview</a>
JavaScript:
JavaScript:
$('.preview').live('click', function(event){
save_survey($(this).attr('href'));
event.preventDefault();
});
function save_survey(url) {
$.ajax({
type: "POST",
url: form_url,
dataType: 'json',
data: form_data,
success: function(data) {
window.open(url, '_blank');
}
});
}
回答by Igor Dymov
I ran into this problem recently and found this work-around:
我最近遇到了这个问题并找到了这个解决方法:
1) call window.open
just before calling $.ajax
and save window reference:
1)window.open
在调用之前调用$.ajax
并保存窗口引用:
var newWindow = window.open(...);
2) on callback set location
property of the saved window reference:
2) 关于location
保存的窗口引用的回调设置属性:
newWindow.location = url;
Maybe it will help you too.
也许它也会帮助你。
回答by albertein
Popup blockers usually works blocking every popup shown not triggered by a direct user action, like clicking on a button or a link.
弹出窗口阻止程序通常会阻止显示的每个弹出窗口,而不是由直接用户操作触发,例如单击按钮或链接。
If you use a ajax request on your click event, the request is fired asyncronous from the click event, that's why by the time the ajax request has done its job and you get your event with the response from the request you have lost your chance to trigger a window.open withouth the popup blocker getting in the way, the original click event it's long dead by that time.
如果您在点击事件上使用 ajax 请求,则该请求会与点击事件异步触发,这就是为什么当 ajax 请求完成其工作并且您收到来自请求的响应的事件时,您已经失去了机会触发 window.open 没有弹出窗口阻止程序妨碍,原来的点击事件到那时已经死了。
回答by jfriend00
回答by Stewie
I solved my case by making the Ajax call synchronous. E.g. (with jQuery):
我通过使 Ajax 调用同步解决了我的问题。例如(使用 jQuery):
$("form").submit(function(e){
e.preventDefault();
$.ajax({
async: false,
url: ...,
data: ...,
success: function(results){
if(results.valid){
window.open(...);
}
}
});
return false;
});