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
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 i.e. $.ajax.Request.done and $.ajax.Request.fail. $.ajax.Request.done(function(){ if(success){ // Implement logic } });
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