【发布时间】:2016-03-25 17:43:10
【问题描述】:
我有一个由 JSON 制成的表格,每一行都有一个按钮,当您单击它时,会调用一个传递元素 ID 的 Web 服务。 Web 服务尝试从数据库中删除元素,如果可以删除,则返回一个简单的 JSON,其中包含属性“状态”和两个可能的值“ERASED”(如果已删除)或“IN_USE”(如果没有)。当我单击按钮时,Web 服务回答正常(实际上是“IN_USE”)。但是,当我尝试读取“状态”值以显示消息时(取决于它是“IN_USE”还是“ERASED”),它会返回“未定义”并且不知道为什么。我一直在做一些技巧,但仍然不起作用。我还用 slim framework 2 做了 web 服务。
控制器(只是有问题的功能):
$scope.show = function (id) {
$http.get('http://10.0.203.73/WS/ws.php/tipusactius/edita/elimina/' + id + '.json').success(function (data) {
$scope.sts = data.status;
$window.alert($scope.sts);
});
if ($scope.sts.status == 'IN_USE') {
$window.alert('Aquest atribut no es pot eliminar perque és en ús');
}
}
有 web 服务(使用 slim 框架 2 完成):
$app->get('/tipusactius/edita/elimina/:id.json', function($id){
header("Content-Type: application/json");
$SQL = 'DELETE FROM atributs_actiu WHERE idatributs_actiu = '.$id;
error_log('DELETE STATEMENT: '.$SQL, 0);
$mysqli = getDB();
$r = $mysqli->query($SQL);
error_log(mysqli_error($mysqli));
if(!$r){
$results[] = array( 'status' => 'IN_USE' );
}
else{
$results[] = array( 'status' => 'ERASED' );
}
echo json_encode($results);
});
Web 服务运行正常,但是当我尝试检查状态值时,控制台上出现未定义。
已解决:
这个案例有两个错误: 1-功能是异步的,所以即使我从服务器得到一些东西,消息仍然可能是“未定义的” 2-我没有适当地缓存“状态”值。
这就是我最终做到的: $scope.sts[0].status
正如 Marius Wirtherle 所说,$http.get 函数中的所有这些:
您的问题可能是 $http 请求被执行 异步。所以当你做的时候请求还没有完成 $window.alert
像这样修改您的代码以使用等待 $http Promise 解决:
$scope.show = function(id){ $http.get('http://10.0.203.73/WS/ws.php/tipusactius/edita/elimina/' +id + '.json') .then(function(response){ // 成功回调(.success 已弃用) $scope.sts = response.data.status; if ($scope.sts == 'IN_USE') { $window.alert('Aquest atribut no es pot eliminar perque és en ús'); } }, function(response){ //错误回调 $window.alert(response.statusText); }); }
关于 $http 的进一步阅读: https://docs.angularjs.org/api/ng/service/$http
【问题讨论】:
标签: angularjs json web-services parsing slim