ajax回调中window.open弹出的窗口会被浏览器拦截的解决方法

今天处理页面ajax请求成功之后用window.open()时被浏览器拦截

然后我百度了很多方法比如

1:下面两种封装的方法放到ajax中不起效

(1)

function newOpenWindow(url, id) {
    var a = document.createElement(‘a‘);
    a.setAttribute(‘href‘, url);
    a.setAttribute(‘target‘, ‘_blank‘);
    a.setAttribute(‘id‘, id);
    // 防止反复添加
    if (!document.getElementById(id)) {
        document.body.appendChild(a);
    }
    a.click();
}

(2)

function newOpenWindow(url) {
    var a = $('<a href="' + url + '" target="_blank"></a>')[0];
    var e = document.createEvent('MouseEvents');
    e.initEvent('click', true, true);
    a.dispatchEvent(e);
}

2:通过定时器,无效(时间长短无关)

var newOpenWindow = window.open();
setTimeout(function() {
    newOpenWindow.location = locationurl;
}, 1000);

最终的解决方法如下

var newOpenWindow = window.open('about:blank'); // 在ajax外部先打开空白新窗口
$.ajax({
    success: function(data) {
        if (data) {
            //window.open('http://www.jb51.net'); 这种方法会被浏览器拦截     (错误方法)
            newOpenWindow.location = "http://www.baidu.com"; //异步成功之后再给新窗口的localtion赋值
        }
    }
})

3:当遇到两层回调的时候,不用先弹页面的时候会出问题。

这次 解决方法:async:false, 把所有的请求都改成同步解决的,但是有隐患。