我正在向Laravel控制器提交数据,并且试图访问返回的Json响应。
我要提交以下数据:
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
data: {ingredients: step_ingredients, description: step_description},
dataType:'json',
url: "{{ route('steps.store', ['id' => $recipe->id]) }}",
success: function (data) {
console.log(data);
//alert(data.desc);
$("#ajaxOutput").html('<code>Description output: '+data.desc+'</code>');
// $.each(data, function (key, value) {
// alert(data.ing.ingredient_id);
// });
},
error: function (xhr, ajaxOptions, thrownError) {
console.warn(xhr.responseText);
alert(xhr.status);
alert(thrownError);
}
});
(现在),控制器正在执行以下操作:
public function store(Request $request)
{
$data = [
'success' => true,
'message'=> 'Your AJAX processed correctly',
'ing' => json_decode($request->ingredients),
'desc' => $request->description
] ;
return response()->json($data);
}
我可以使用data.desc
访问描述等,但是在遍历data.ing
数组并访问相关值(例如成分1名称)时遇到问题,或者成分2数量。
答案 0 :(得分:4)
尝试
对于laravel
foreach($ing as $data) {
echo "$data->ingredient_name"; //$data is object
}
对于javascript
$.each(data.ing, function (key, value) { console.log(value.ingredient_name); })