在 Ajax 成功上循环遍历对象内的数组内的对象

Posted

技术标签:

【中文标题】在 Ajax 成功上循环遍历对象内的数组内的对象【英文标题】:Loop through Object within Array within Object on Ajax Success 【发布时间】: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 个数量

【问题讨论】:

【参考方案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,但这是可行的。谢谢!

以上是关于在 Ajax 成功上循环遍历对象内的数组内的对象的主要内容,如果未能解决你的问题,请参考以下文章

ajax成功内的Ajax调用不起作用

如何将 JSON 对象内的 JSON 数组传递给 jQuery 自动完成

操作数组对象内的数据[重复]

js 数组遍历时删除元素

java语言如何循环读取Map对象内的数据

ajax中如何把传递过来的json数据循环遍历出