【发布时间】:2016-11-19 23:38:27
【问题描述】:
我正在尝试从我的 Angular 应用程序的请求中访问对象属性。我正在使用 Laravel 5.1
角度:
console.log('getQuestionAnswers', params);
return $http({
method: 'GET',
url: url + ver + '/questions/checkMany',
params: {
'questions[]' : params
},
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + $rootScope.access_token
},
cache: true
});
参数的控制台.log:
Laravel:
public function getAnswers(Request $request)
{
$input = $request->all();
$question_objs = $input['questions'];
foreach ($question_objs as $question_answer_object) {
return $question_answer_object;
回复 Angular:return $question_objs;
回复 Angular:return $question_answer_object;
看起来到目前为止一切都很好!
但如果我尝试访问 laravel 中的属性,例如 question_id:
return $question_answer_object['question_id'];
我得到错误:
"非法字符串偏移'question_id'
Laravel 已经解析了 JSON,
// From Illuminate/Http/Request.php all() method:
if (! isset($this->json)) {
$this->json = new ParameterBag((array) json_decode($this->getContent(), true));
}
当我返回它时,我可以看到它是一个对象。为什么我无法访问属性?我也试过 json_decode 没有运气。
使用 JSON 解码:
$test = json_decode($question_answer_object, true);
return $test['question_id'];
这似乎有效。但是为什么呢?
像这样访问对象的属性:
return $question_answer_object->question_id;
给出以下错误:
"试图获取非对象的属性"
【问题讨论】:
-
@ChoncholMahmud 请参阅上面的 json 解码尝试
-
@ChoncholMahmud 好的,它起作用了。但我认为 Laravel 的
$request->all()是return array_replace_recursive($this->input(), $this->files->all());和递归json_decodes?你能解释一下吗?
标签: php angularjs json laravel laravel-5.1