【发布时间】:2017-01-21 21:11:23
【问题描述】:
我的 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);
如何从 JSON 中检索“令牌”值?
如果 JSON 有多个“结果”条目,我如何循环访问它?
【问题讨论】:
-
在 JS 中可以通过索引访问:
jsParse['stoken'] -
>>中的json返回[{\"result\":{\"status\":1,\"message\":\"Token生成成功\",\"stoken\" ?:\ “eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImp0aSI6IjVmMXoyaTNhbDJ4eCJ9.eyJpc3MiOiJodHRwOlwvXC9lc2FsZXMuY29tIiwiYXVkIjoiZVNhbGVzIiwianRpIjoiNWYxejJpM2FsMnh4IiwiaWF0IjoxNDczODQ4OTk1LCJuYmYiOjE0NzM4NDkwNTUsImV4cCI6MTQ3Mzg1MjU5NSwidWlkIjoiYWRtaW4iLCJ1Z3JwIjoic2FsZXMifQ.MJLIYAslvJp_rSmPUEnFK7ZjYLx2tv8ydhTY3nYtbRA \”}}]
-
你试图解析的数据(
var jsParse = JSON.Parse(data);已经是JSON了。所以你只需要做var token = data['stoken];。抱歉误导了你。
标签: php json ionic-framework jwt