gpt4 book ai didi

javascript - 如何使用 Angular JavaScript 从(php 编码的 json)获取值?

转载 作者:行者123 更新时间:2023-12-03 10:47:07 25 4
gpt4 key购买 nike

在控制台中我只能看到成功,而 $scope.data.username 没有打印任何内容。第二个问题:在我的 php 中我需要发送 status 和 status_massage 吗?为什么?

在我的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');
});
};

在 postman 中它将返回

    {
"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;

最佳答案

目前您已将 statusstatus_messagedata 合并到响应正文中,该正文被视为 data 在 Angular 的 success(function(data, status, headers, config) {}) 中。因此,一个快速而肮脏的修复方法是在成功回调中使用 $scope.data = data.data

但是,这并不是将所有内容合并到响应正文中的正确方法。对于 HTTP response code ,你应该设置为

<?php
http_response_code(200);
?>

而对于您的响应正文,您只需将用户名设置为

$response['username'] = @user   
$jsonResponse = json_encode($response);
echo $jsonResponse;

这样您就不会更改当前的 Angular 代码。

关于javascript - 如何使用 Angular JavaScript 从(php 编码的 json)获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28533834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com