在Ajax成功时在对象内的数组内遍历对象

时间:2018-06-26 12:34:10

标签: arrays json ajax laravel ajaxform

我正在向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);
}

Console Log of data response

我可以使用data.desc访问描述等,但是在遍历data.ing数组并访问相关值(例如成分1名称)时遇到问题,或者成分2数量

1 个答案:

答案 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); })

相关问题