poc*_*sar 11 ajax popup window.open twitter-oauth facebook-oauth
当从服务器(例如Twitter和Facebook)处理OAuth时,您很可能会将用户重定向到要求获得应用程序权限的URL.通常,在单击链接后,您通过AJAX将请求发送到服务器,然后返回授权URL.
但是当你window.open在收到答案时尝试使用时,你的浏览器会阻止弹出窗口,使其无效.当然,您可以将用户重定向到新的URL,但这会破坏用户体验,而且令人讨厌.您不能使用IFRAMES,但不允许使用IFRAMES(因为您无法看到位置栏).
那怎么办呢?
poc*_*sar 27
答案很简单,跨浏览器可以毫无问题地工作.在进行AJAX调用时(我将在本例中使用jQuery),只需执行以下操作即可.假设我们有一个带有两个按钮的表单,Login with Twitter并且Login with Facebook.
<button type="submit" class="login" value="facebook" name="type">Login with Facebook</button>
<button type="submit" class="login" value="twitter" name="type">Login with Twitter</button>
Run Code Online (Sandbox Code Playgroud)
然后是魔术发生的Javascript代码
$(function () {
var
$login = $('.login'),
authWindow;
$login.on('click', function (e) {
e.preventDefault();
/* We pre-open the popup in the submit, since it was generated from a "click" event, so no popup block happens */
authWindow = window.open('about:blank', '', 'left=20,top=20,width=400,height=300,toolbar=0,resizable=1');
/* do the AJAX call requesting for the authorize URL */
$.ajax({
url: '/echo/json/',
type: "POST",
data: {"json": JSON.stringify({"url": 'http://' + e.target.value + '.com'})}
/*Since it's a jsfiddle, the echo is only for demo purposes */
})
.done(function (data) {
/* This is where the magic happens, we simply redirec the popup to the new authorize URL that we received from the server */
authWindow.location.replace(data.url);
})
.always(function () {
/* You can poll if the window got closed here, and so a refresh on the main page, or another AJAX call for example */
});
});
});
Run Code Online (Sandbox Code Playgroud)
这是JSFiddle中的POC http://jsfiddle.net/CNCgG/
这很简单有效:)
尝试添加async:false.它应该工作
$('#myButton').click(function() {
$.ajax({
type: 'POST',
async: false,
url: '/echo/json/',
data: {'json': JSON.stringify({
url:'http://google.com'})},
success: function(data) {
window.open(data.url,'_blank');
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17331 次 |
| 最近记录: |