如何防止数字字符串数组在Javascript中向上/向下舍入?

时间:2016-05-26 12:01:36

标签: javascript arrays facebook facebook-graph-api

我正在使用HTML& amp;创建Facebook游戏Javascript,我正在努力奖励人们邀请其他人加入游戏。要做到这一点,我会在新玩家加入时运行检查 - 我查询Facebook的Graph API以获取已邀请新玩家的人员ID列表。

我的问题是这个,这个查询返回一个ID数组,这很好,但似乎ID作为整数返回,并且因为Javascript对数组中的整数大小有限制,其中一些ID正在向上或向下舍入1个数字。这意味着某些ID不正确。

我正在使用Ajax Post将此数组发送到我的数据库,但是php文件失败了,因为我的数据库中不存在舍入的ID。

我的数据库中的ID列是VARCHAR,所以我认为如果数据是以字符串格式而不是int发送的,那么php文件将会起作用。我知道如果Javascript将它们存储为字符串而不是int,那么Javascript在数组中存储正确的ID没有问题。

我的问题是,如何将Graph API调用的响应存储为字符串,而不是int? Facebook的文档:https://developers.facebook.com/docs/graph-api/reference/user/apprequests/表示当您阅读用户的apprequests时,您会收到AppRequest节点列表。此页面(在AppRequest节点上)https://developers.facebook.com/docs/graph-api/reference/app-request/表示from参数作为User对象返回。此页面(在User对象上)https://developers.facebook.com/docs/graph-api/reference/user/表示ID作为“数字字符串”返回。但是,在Javascript中仍在进行四舍五入。

这是对图谱API的查询:

function getRequests() {

FB.login(function(response) {
  if (response.authResponse) {
    console.log('Welcome!  Fetching your information.... ');

//This is the call to Facebook...
     FB.api('me/apprequests?fields=to,from,id', function(response) {

     if (response.error) {
       console.log('Error - ' + response.error.message);
     }
     else {

    var requestid = [];

//Iterating through the response, and inserting all "from" IDs into the array...
    for(var i = 0; i < response.data.length; i++){
    requestid.push(response.data[i].from.id);
    }

    console.log(requestid);

//Sending the array to the database...
       $.ajax({
        url: 'php_scripts/sendinviterewards.php',
        data: {'requestid' : requestid},
        type: "POST",
        success: function(response){
            console.log(response);
                    }
       });
     }
    });
  } else {
    console.log('User cancelled login or did not fully authorize.');
  }
 }, {scope: 'email, user_birthday'});
}

也许ID作为数字字符串返回,但我使用Javascript导致更大的ID号被舍入。如果是这种情况,那么解决这个问题的最佳方法是什么?我需要使用其他语言吗?或者是否有一些使用Javascript的工作?提前谢谢!

1 个答案:

答案 0 :(得分:0)

我不完全确定导致这种情况的原因,但你可以试试这个:

for(var i = 0; i < response.data.length; i++){
    var id = new String(response.data[i].from.id);  
    requestid.push(id);
}