简体   繁体   中英

window.open() works different on AJAX success

It will be more easy for me to explain the problem if I just show you that example -> http://jsfiddle.net/RU2SM/
As you can see there are 2 buttons, one called'AJAX' and one called 'Direct'... So if you click on 'Direct' it opens window (new tab on Chrome) but if I try to make window.open() on AJAX success handler, it doesn't work same way.
I'm sure that the problem is from AJAX but I have no idea how to fix it.
Will appreciate any good ideas. Thanks

This works like a charm:

// Direct window.open()
$('#btnDirect').on('click',function(){
    window.open('http://google.com')
})
var success = false;  //NOTE THIS

// AJAX window.open()
$('#btnAJAX').on("click", function(){
    $.ajax({
      url: "/user/login/",
      context: document.body,
      async:false,   //NOTE THIS
      success: function(){  //THIS ALSO CHANGED
         success = true
      }
    });
    if(success){ //AND THIS CHANGED
      window.open('http://google.com')
    }
})

What this does is when the Ajax call is success it sets the variable success to true.
The async:false propperty makes sure that the if statement is fired after the Ajax call is completed.
So the window.open is fired in the same circumstances as your direct link.

The issue is that browsers will often block window.open s unless they're called in direct response to a user action. That's why your click handler works (a click is a user action) but your AJAX handler doesn't.

One solution is to open the window during the initial click action, then update its location on AJAX success (or close it again on AJAX failure).

Otherwise you'll have to get the user to explicitly allow popups from your domain in their browser.

Better way implement any logic after success of ajax call, there is an event fired on every ajax call execution ie $.ajax.Request.done and $.ajax.Request.fail . $.ajax.Request.done(function(){ if(success){ // Implement logic } });

另外值得一提的是,使用 async: false 然后调用 window.open 可以在 chrome 和 firefox 中工作,但可能会导致 safari 出现问题......它甚至没有提供弹出窗口被阻止的信息

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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