Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

javascript - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...