Javascript 数据未从localStorage PHP发布。有棱角的
我正在尝试为体育赛事创建某种订阅。在本例中,我创建了带有gameId和userId的表。我正在尝试通过localStorage登录用户id。 这是我的角度代码:Javascript 数据未从localStorage PHP发布。有棱角的,javascript,php,angularjs,Javascript,Php,Angularjs,我正在尝试为体育赛事创建某种订阅。在本例中,我创建了带有gameId和userId的表。我正在尝试通过localStorage登录用户id。 这是我的角度代码: app.controller('customersCtrl', function($scope, $http) { $http.get("php/contents.php") .then(function (response) { $scope.games = response.data.games; }); /*$scope.
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);
?>
当我控制台$data时,我得到对象{userId:“↵1“,gameId:“2”},但在数据库中只有gameId,userId总是=0
我会非常感谢你的帮助
localStorage
仅存储字符串
假设您使用的是JSON.stringify()
当您使用setItem()
时,您需要使用JSON.parse()
试一试
注意:在传递到请求之前,还应确保密钥存在于localStorage中
或者,如果要执行以下操作,请使用php:
$userId= json_decode($data->userId);
您还应该看到正确的db insert,但是在发布时混合数据类型似乎不一致,并且在以后进行维护时可能会混淆
$userId= json_decode($data->userId);