在jQuery ajax成功回调中创建弹出窗口时被阻止 [英] Popup blocked when created in jQuery ajax success callback

查看:183
本文介绍了在jQuery ajax成功回调中创建弹出窗口时被阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google Chrome浏览器似乎阻止了我通过jQuery创建的弹出窗口.经过一些调查,在ajax调用成功的情况下,调用window.open似乎是一个问题.有没有解决的办法?我的jQuery ajax调用返回要打开的URL.所以我有点卡住.

Google Chrome seems to be blocking a popup I am creating via jQuery. After some investigation, it appears to be an issue with calling window.open in the success event of an ajax call. Is there a way around this? My jQuery ajax call returns the URL to be opened. So I am bit stuck.

如果我将window.open放在ajax调用之外,它将起作用;但是在内部(即成功事件中)它被阻止了.我认为这与CONTEXT有关,但我不确定.

It works if I place the window.open outside the ajax call; but, inside (i.e. in the success event) it is blocked. I think it is something to do with CONTEXT but I am unsure.

这就是我所拥有的:

     window.open("https://www.myurl.com");  // OUTSIDE OF AJAX - no problems 
                                            // with popup

     $.ajax({
        type: "POST",
        url: "MyService.aspx/ConstructUrl",
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            // Normally loads msg.d which is the url returned from service
            // static url below is for testing
            window.open("https://www.myurl.com");  // THIS IS BLOCKED
        },
        error: function(msg) {
            // alert(error);
        }
    });

推荐答案

只需在成功回调中打开新窗口:

Simply open the new window in the success callback:

 $.ajax({
    type: "POST",
    url: "MyService.aspx/ConstructUrl",
    data: jsonData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        window.open("https://www.myurl.com"); 
    },
    error: function(msg) {
        //alert(error);
    }
});

请注意,您可能需要为此将$ .ajax的async选项设置为false,否则可以在收到响应之前对$ .ajax调用之后的代码进行评估.

Note you might have to set $.ajax's async option to false for that, otherwise the code following the $.ajax call could be evaluated before the response is received.

这篇关于在jQuery ajax成功回调中创建弹出窗口时被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆