我发现了很多关于如何将隐藏输入字段值传递给 angularjs 脚本的资源,但如果从 php session 读取该值则不会。
这是我的 html 代码:
<div ng-controller="ImgCtrl">
<input type="hidden" ng-model="uid" value="<?=$_SESSION["uid"];?>" >
<input type="file" ng-file-select="onFileSelect($files)" >
<br/>
<span>{{ message }}</span>
</div>
我也试过这样:
<input type="hidden" ng-model="uid" value="{{<?=$_SESSION["uid"];?>}}" >
编辑 处理它的 angularjs 代码是:
var ImgCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: 'image_upload.php',
method: 'POST',
data: {
'uid': $scope.uid
},
file: file
}).success(function(data, status, headers, config) {
$scope.message = data;
}).error(function(data, status) {
alert(data);
});
}
};
}];
这是我找到的答案之一,但我似乎找不到如何在 angularjs 中读取 php session 变量。
有人有想法吗?
谢谢!
最佳答案
第一个也是最简单的方法是创建一个全局 JavaScript 变量并在 PHP 代码中设置该值。然后这将被传递到 Controller 。在 php 页面中,您将拥有:
<script>var serverVariable=<?=$_SESSION["uid"];?>;</script>
在你的 Controller 中你会看到这样一行:
$scope.userId = serverVariable;
之后,您可以在任何您想要的范围内使用 userId,它就会起作用!有一个笨蛋在这里演示了这一点:http://plnkr.co/edit/7xEGM0Rz80TJQc0kPBwz?p=preview .
注释
所以,当然,最简单的事情并不总是最好的事情。首先,如果您在客户端传递用户 ID - 无论是在隐藏变量中还是在 javascript 全局中客户端可以操纵您的值。您不想依赖客户端在“post”或“put”中返回的任何内容 - 但您应该使用在 session 中存储的值。对于任何敏感值来说,这都是一个非常好的经验法则。
另一件事 - 这是最简单的,但它远不是唯一的选择。您可以考虑在定义 Controller 的元素上使用“ng-init”指令。您可以在这里找到带有该答案的堆栈问题:Can you pass parameters to an AngularJS controller on creation? 。同样,只需将服务器端的值传递到 init 例程中,所有内容都应该正确传递到 Controller !
我希望我的回答至少能让您走上正轨。祝你好运!
关于php - angularjs 为隐藏字段提供 'undefined' ,并以 php session 变量作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21104077/