我正在尝试为体育赛事创建某种订阅。在本例中,我创建了包含 gameId 和 userId 的表。我正在尝试通过 localStorage 登录用户 ID。 这是我的 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);
?>
当我控制台 $data 时,我得到对象 {userId: "↵1", gameId: "2"},但在数据库中只有 gameId,userId 始终 = 0。
非常感谢您的帮助!
最佳答案
localStorage
仅存储字符串。
假设您在执行 setItem()
时使用 JSON.stringify()
,则需要执行相反的操作,以使用 JSON 将其从字符串转换为对象.parse()
尝试
var data = {
userId: JSON.parse(localStorage.getItem('loggedUserInfo')),
gameId: gameId
}
请注意,在传递给请求之前,您还应该确保 key 存在于 localStorage 中
如果您要这样做,也可以在 php 中:
$userId= json_decode($data->userId);
您还应该看到正确的数据库插入,但是发布时混合数据类型似乎不一致,并且在以后进行维护时可能会造成困惑
关于javascript - 数据未从 localStorage PHP 发布。 Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39841597/