window.open() works different on AJAX success [duplicate]

血红的双手。 提交于 2019-11-27 13:04:24

问题


Possible Duplicate:
window.open(url) different behavior - same code, different timing

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


回答1:


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.




回答2:


The issue is that browsers will often block window.opens 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.




回答3:


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




回答4:


as an addition it is also worth mentioning that using async: false and then calling window.open works in chrome and firefox but can cause trouble in safari... it doesn't even give an info that a popup was blocked



来源:https://stackoverflow.com/questions/10223388/window-open-works-different-on-ajax-success

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!