2016-10-03 43 views
1

我正在嘗試爲體育賽事創建某種訂閱。在這種情況下,我使用gameId和userId創建了表。我試圖通過localStorage登錄用戶ID。 這裏是我的角度代碼:數據未從localStorage PHP發佈。 Angular

app.controller('customersCtrl', function($scope, $http) { 
$http.get("php/contents.php") 
.then(function (response) { 
    $scope.games = response.data.games; 
}); 
/*$scope.subscribe = function(something){ 
    // console.log(something); 
    console.log(localStorage.getItem('loggedUserInfo')); 
};*/ 
$scope.subscribe = function (gameId,userId){ 
    var data = { 
     userId: localStorage.getItem('loggedUserInfo'), 
     gameId: gameId 
    } 
    //console.log(data);  
    $http.post("php/subscribe.php", data).success(function(response){ 
     console.log(response); 
    }).error(function(error){ 
     console.error(error); 
    }); 
}; 
}); 

這裏是我的PHP代碼:

<?php 
include("../connection.php"); 
$data = json_decode(file_get_contents("php://input")); 
$userId = $data->userId; 
$gameId = $data->gameId; 

$q = "INSERT INTO subscription (gameId, playerId) VALUES (:game, :user)"; 
$query = $db->prepare($q); 
$execute = $query->execute(array(
    ":game" => $gameId, 
    ":user" => $userId 

)); 

echo json_encode($data); 
?> 

當我安慰$的數據,我得到對象{用戶名: 「↵1」,遊戲ID: 「2」},但是在數據庫中只能使用gameId,userId總是= 0.

會非常感謝您的幫助!

回答

1

localStorage只存儲字符串。

假設你正在使用JSON.stringify()當你做setItem()你需要做反向從字符串把它用JSON.parse()

反對嘗試

var data = { 
    userId: JSON.parse(localStorage.getItem('loggedUserInfo')), 
    gameId: gameId 
} 

注意,你也應該確保該鍵存在在localStorage也傳遞到請求之前

另外在php中,如果你要這樣做:

$userId= json_decode($data->userId); 

你也應該看到合適的分貝插入但是混合數據類型時發佈似乎不一致,可能以後做保養

+0

混淆謝謝你,兄弟。有用! –