在控制台中,我只能看到成功,而$scope.data.username什么也不打印。还有第二个问题:在我的php中,我需要发送状态和状态按摩吗?为什么?
在我的js:
$scope.register = function register() {
$http.post('.../api/user.php', {username: $scope.user.username, password: $scope.user.password, func: 'register'}).
success(function(data, status, headers, config) {
console.log('succes');
$scope.data = data;
console.log($scope.data.username);
}).
error(function(data, status, headers, config) {
console.log('error');
});
};
在邮递员那里,它会返回
{
"status": 200,
"status_message": "OK",
"data": {
"username": "smith99"
}
}
我的php脚本做到了:
$response['status'] = 200;
$response['status_message'] = "OK";
$response['data'] = array(
'username' => $user
);
$jsonResponse = json_encode($response);
echo $jsonResponse;
目前您已经将status
、status_message
和data
合并到您的响应体中,在Angular的success(function(data, status, headers, config) {})
中被视为data
。因此,一个快速而肮脏的修复方法是在成功回调中使用$scope.data = data.data
。
然而,将所有内容合并到响应体中并不是一种合适的方式。对于HTTP响应代码,您应该设置为
<?php
http_response_code(200);
?>
而对于您的响应主体,您可以简单地将username
设置为
$response['username'] = @user
$jsonResponse = json_encode($response);
echo $jsonResponse;
这样就不会更改当前的Angular代码。