【问题标题】:Loop through Object within Array within Object on Ajax Success在 Ajax 成功上循环遍历对象内的数组内的对象
【发布时间】:2018-12-05 04:26:28
【问题描述】:

我正在向我的 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 数组和访问相关值时遇到问题,例如 ingredient 1 nameingredient 2 个数量

【问题讨论】:

    标签: arrays json ajax laravel ajaxform


    【解决方案1】:

    试试 对于 laravel foreach($ing as $data) { echo "$data->ingredient_name"; //$data is object }

    对于 javascript

    $.each(data.ing, function (key, value) { console.log(value.ingredient_name); })

    【讨论】:

    • 我使用了以下内容:$.each(data.ing as $data) { console.log($data-&gt;ingredient_name); //$data is object }; 和它的一些迭代,并不断收到“意外的标识符 'as'。预期的 ')' 来结束参数列表。”
    • 试试$.each(data.ing, function (key, value) { console.log(value-&gt; ingredient_name); });
    • 我不得不将其更改为 value.ingredient_name,但这是可行的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-05-21
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多