繁体   English   中英

触发 window.open 作为 ajax 完成

[英]Trigger window.open as ajax complete

在一个网站中,有一些 jQuery ajax 调用,在其中一些调用中,如果成功,则会触发另一个域中的 winwdow.open。 我拥有其他域站点。

例如:

  1. 站点https://site1.example.com对自身进行 ajax 调用
  2. 如果成功在https://site1.example2.comhttps://site2.example.com上触发 window.open
  3. 通常弹出窗口阻止程序会阻止操作

我该如何处理这个问题? 我是否必须在我的站点/服务器https://enable-cors.org/上启用 CORS?

代码(当然,我没有谷歌):

$.ajax({
    url:'/echo/js/?js=hello%20world!',
    complete: function (response) {
        $('#output').html(response.responseText);
        window.open('https://www.google.com');
    },
    error: function () {
        $('#output').html('Bummer: there was an error!');
    },
});

演示: https : //jsfiddle.net/IrvinDominin/nbsu3hgk/

我最近遇到了和你一样的问题。 就我而言,我需要在打开新页面之前执行一些操作。 我要求将新页面打开到锚标记,并使用 preventDefault 方法来避免在操作返回否定结果时打开。

<a href="https://www.google.com" targe="_blank" onclick="doSomeOperation(event)">text</a>  

<script>
function doSomeOperation(event){
$.ajax({
    async:false,
    url:'/echo/js/?js=hello%20world!',
    complete: function (response) {
        $('#output').html(response.responseText);
    },
    error: function () {
        event.preventDefault();
        $('#output').html('Bummer: there was an error!');
    },
});
}
</script>

因为window.open需要用户直接操作(例如单击)以避免弹出窗口阻止程序,您可以像这样更改代码:

$.ajax({
    url:'/echo/js/?js=hello%20world!',
    complete: function (response) {
        $('#output').html(response.responseText);
        //window.open('https://www.google.com');
        $( "body" ).append('<button id="openPopup">Open Site</button>');
        $( "#openPopup" ).click( function() { 
                window.open('https://www.google.com');
        });
    },
    error: function () {
        $('#output').html('Bummer: there was an error!');
    },
});

如果 ajax 请求成功,用户会看到一个按钮,他们必须点击该按钮才能进入其他域。

编辑:参考您在下面的评论,我想我找到了解决方案:

var myPopup;
$( document ).on("click", "#myButton", function() {
    myPopup = window.open("/");

    $.ajax({
        url:'/echo/js/?js=hello%20world!',
        complete: function (response) {
            $('#output').html(response.responseText);
            //window.open('https://www.google.com');
            myPopup.location.href = 'https://www.google.com';
        },
        error: function () {
            $('#output').html('Bummer: there was an error!');
        },
    });
});

您必须首先为新窗口声明一个全局变量。 当您点击触发 ajax 请求的按钮时,您会打开一个新窗口,该窗口引用您当前的域(在您的情况下为https://site1.example.com/ )。 这被接受为直接的用户操作,因此没有弹出窗口阻止程序生效。

complete功能中,您将该窗口重定向到其他域之一( https://site1.example2.comhttps://site2.example.com ),等等。 我已经使用激活的弹出窗口阻止程序对其进行了测试,并且可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM