This is the case: our background staff have a requirement to open a page in a new window in the callback function after the Ajax request is successful. The sample code is as follows:
$("#btn").on("click",function(){ $.ajax({ url : "opendata.html", type : "post", data : {"a" : 1}, success : function(){ window.open("http://www.baidu.com") } })})
However, this cannot be done, and the browser will block the opening of the page. So I sorted out how to bypass this problem on the Internet and tested it (I tested IE, Firefox, Google, Safari). Now I want to talk about my testing situation:
There are three ways to bypass this problem. The first method code is as follows:
$("#btn").on("click",function(){ var tempWin = window.open("","_blank") $.ajax({ url : "opendata.html", type : "post", data : {"a" : 1}, success : function(){ tempWin.location = "http://www.baidu.com" } })})
This method opens a blank window before Ajax requests, and then changes the window URL implementation in the callback. in windows, all browsers I tested are OK, you can open the page in a new window.
The code for the second method is as follows:
function openwin(url) { var a = document.createElement("a"); a.setAttribute("href", url); a.setAttribute("target", "_blank"); a.setAttribute("id", "openwin"); document.body.appendChild(a); a.click();}$("#btn").on("click",function(){ $.ajax({ url : "opendata.html", type : "post", data : {"a" : 1}, async : false, success : function(){ openwin("http://www.baidu.com") } })})
This method uses the label to simulate window. open (). However, you must change ajax to the synchronous method in this method. Otherwise, the new page will still be blocked. It should be noted that, even if the synchronous method is adopted, the Safari browser will never open the page.
The code for the third method is as follows:
function openUrl( url ){ var f=document.createElement("form"); f.setAttribute("action" , url ); f.setAttribute("method" , ‘get‘ ); f.setAttribute("target" , ‘_black‘ ); document.body.appendChild(f) f.submit();}$("#btn").on("click",function(){ $.ajax({ url : "opendata.html", type : "post", data : {"a" : 1}, async : false, success : function(){ openUrl("http://www.baidu.com") } })})
Similar to the second method, the form label is used to simulate window. open (). Similarly, you also need to change ajax to a synchronous method. Fortunately, the safafi browser can use this method to open a new page.
The above test results are all in windows. We switched to the Apple system, and safari in the Apple system failed these three methods.
Through the above test, opening a new page in the callback is not desirable.
Browser blocking of opening pages in new windows