Ajax不会发送所有数据

时间:2015-08-09 18:26:47

标签: javascript php jquery ajax

我的请求有问题。看看这段代码

logInWithFacebook = function() {
FB.login(function(response) {
  if (response.authResponse) {
     FB.api('/me', {fields: 'name,email,location,picture'},function(userInfo) {

         FB.api('/me/picture?type=normal', function (response) {
            userInfo.photo = response.data.url; // what's wrong with that?
          });

          if(userInfo.location)
          {
            var location = userInfo.location.name.split(",");
            userInfo.location = location[0];
          }

        $.ajax({
            data:userInfo,
            type:"POST",
            url:"/login/facebook-loginexecute",
            dataType: "json",
            beforeSend: function() {
            console.log(userInfo); // everything is showing
            },
            success: function(result) {

            }
        });         
    });
  } 
},{scope: 'public_profile,email,user_location'});
return false;

};

因此,在通过ajax发送数据(在本例中为#34; userinfo")之后,PHP函数print_r - 返回所有没有元素的$ _POST - photo。我不知道为什么? '

1 个答案:

答案 0 :(得分:0)

我的猜测是FB.api调用是异步的,所以你在后台触发它,然后在执行FB.api成功回调之前激活你自己的ajax调用。

在FB.api回调中移动你的ajax调用:

logInWithFacebook = function() {
    FB.login(function(response) {
        if (response.authResponse) {
            FB.api('/me', {
                fields: 'name,email,location,picture'
            }, function(userInfo) {

                FB.api('/me/picture?type=normal', function(response) {
                    userInfo.photo = response.data.url; // what's wrong with that?

                    if (userInfo.location) {
                        var location = userInfo.location.name.split(",");
                        userInfo.location = location[0];
                    }

                    $.ajax({
                        data: userInfo,
                        type: "POST",
                        url: "/login/facebook-loginexecute",
                        dataType: "json",
                        beforeSend: function() {
                            console.log(userInfo); // everything is showing
                        },
                        success: function(result) {

                        }
                    });

                });

            });
        }
    }, {
        scope: 'public_profile,email,user_location'
    });
    return false;
};

至于为什么它会在控制台中显示,控制台可能会维护对象的引用,当你查看它时,初始请求已经完成。