我想只在Ajax成功时触发功能
我的功能ajax
$.ajax({
type: "POST",
url: url,
dataType: "json",
success: function(msg) {
console.dir(msg);
if(msg.status == 'OK'){
$("#fb-root").on("facebook:init", function(event, response) {
if(response.status === 'connected') {
alert("LOG")
}else{
alert(" NO LOG ");
}
});
}
}
});
触发功能
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
$('#fb-root').trigger('facebook:init',[response]);
} else if (response.status === 'not_authorized') {
$('#fb-root').trigger('facebook:init',[response]);
} else {
$('#fb-root').trigger('facebook:init',[response]);
}
});
}
从不alert("LOG")
或alert("NO LOG");
如果我使用
$("#fb-root").on("facebook:init", function(event, response) {
if(response.status === 'connected') {
alert("LOG")
}else{
alert(" NO LOG ");
}
});
在ajax之外,它的作品
由于
答案 0 :(得分:1)
我认为你需要这个:
//Move this function outside ajax as this is to register event handler, not to trigger the function.
$("#fb-root").on("facebook:init", function(event, response) {
if(response.status === 'connected') {
alert("LOG")
}else{
alert(" NO LOG ");
}
});
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
$('#fb-root').trigger('facebook:init',[response]);
} else if (response.status === 'not_authorized') {
$('#fb-root').trigger('facebook:init',[response]);
} else {
$('#fb-root').trigger('facebook:init',[response]);
}
});
}
$.ajax({
type: "POST",
url: url,
dataType: "json",
success: function(msg) {
console.dir(msg);
if(msg.status == 'OK'){
getLoginStatus(); //only trigger the function when ajax is successful.
//or $('#fb-root').trigger('facebook:init',msg);
}
}
});
$("#fb-root").on("facebook:init"
是注册事件处理程序,而不是触发事件。您应该始终在$ .ajax函数之外添加事件处理程序,并触发它在您的成功函数内部启动。