Ajax内部触发器成功

Trigger inside Ajax success

本文关键字:成功 触发器 内部 Ajax      更新时间:2023-09-26

我只想在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之外,它的工作原理是

感谢

我想你需要这个:

    //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函数外部添加事件处理程序,并在成功函数内部触发它。