从REST API中提取JSON响应

时间:2016-09-14 06:45:21

标签: php json ionic-framework jwt

我的API返回以下JSON响应:

[{"result":{"status":1,"message":"Token generated successfully","stoken":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImp0aSI6IjVmMXoyaTNhbDJ4eCJ9.eyJpc3MiOiJodHRwOlwvXC9lc2FsZXMuY29tIiwiYXVkIjoiZVNhbGVzIiwianRpIjoiNWYxejJpM2FsMnh4IiwiaWF0IjoxNDczODMwNDExLCJuYmYiOjE0NzM4MzA0NzEsImV4cCI6MTQ3MzgzNDAxMSwidWlkIjoiYWRtaW4iLCJ1Z3JwIjoic2FsZXMifQ.eeFU68UdAIkZuWtSK8H0mfJRsGM0aaCdZ2MJX4ZQUF0"}}]

我在Ionic的代码:

.controller('loginCtrl', ['$scope', '$http', function ($scope, $http ) {
    $scope.data = {}; 

    $scope.submit = function(){
        var link = 'http://myapi.com/jwt/auth/';

        $http.post(link, {username : $scope.data.username, password : $scope.data.password})
        .success(function(data, status, headers,config){
            $scope.response = data; // for UI

            var jsParse = JSON.parse(data)      

            //how to retrieve the 'stoken' value from the JSON ?


        })
        .error(function(data, status, headers,config){
          console.log('data error');
        })
        .then(function (res){
            $scope.response = res.data;

        });
    };
}])

生成json的PHP代码:

    $responses[] = array('result'=> 
                    array( 'status' => 1, 
                           'message' => 'Token generated successfully', 
                           'stoken' => ''.$token,
                        )
                    );

    //return json_encode(['result' => 1, 'message' => 'Token generated successfully', 'token' => '' . $token,]);
     return json_encode($responses);
  1. 如何检索' stoken'来自JSON的价值?

  2. 如果JSON有多个'结果'条目?

1 个答案:

答案 0 :(得分:0)

$http.post(link, {username : $scope.data.username, password : $scope.data.password})
        .success(function(data, status, headers,config){
            $scope.response = data;
  
            $scope.stoken =  $scope.response[0].result.stoken;
        


        })
        .error(function(data, status, headers,config){
          console.log('data error');
        })
        .then(function (res){
            $scope.response = res.data;

        });

不需要JSON.parse,angular使用http拦截器自动为您执行此操作,并且您的响应对象已包含JSON对象。