【问题标题】:Cannot access data of deserialized json无法访问反序列化 json 的数据
【发布时间】:2020-05-24 22:25:45
【问题描述】:

我正在使用 ajax 将数据发送到我的控制器,这是我的做法

var formData = JSON.stringify( $('#SubmitForm').serializeArray() );
$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});
$.ajax({
  type: 'POST',
  data: {formData},
  url: '{{route("fileController.sendFiles")}}',
  success: function(response) {
    console.log(response);
  },
  error: function(response){
    console.log(response);
  }
});

这是路线

Route::post('/sendFiles', ['uses' => 'FileController@sendFiles'])->name('fileController.sendFiles');

还有控制器

public function sendFiles(Request $request)
{
  //$data = json_decode($request->input('formData'), true);
  //return $request->input('allFiles');
  $data = json_decode($request->input('formData'), true);
  return $data['allFiles'];
}

但是,我得到了这个错误

"message": "Undefined index: allFiles"

当我查看$request的内容时,我可以看到allFiles数组显然在那里,但是我如何访问它呢? 附言我试过在解码时将第二个参数更改为false,没有区别。

$request data array

【问题讨论】:

    标签: json ajax laravel post


    【解决方案1】:
    • 首先,您的请求数据是简单的对象数组。所以你不能用“allFiles”来索引它。
    • 其次,由于我们有多个属性名称为“allFiles[]”的对象,因此您可以过滤这些对象并返回它们的值。 (我不知道你打算如何使用它,但代码看起来是这样的)
    public function sendFiles(Request $request)
    {
      //$data = json_decode($request->input('formData'), true);
      //return $request->input('allFiles');
      $data = json_decode($request->input('formData'), true);
      //filter all allFiles object
      $allFiles = array_filter($data, function($obj){ 
                 if(isset($obj->name)){
                    return $obj->name=="allFiles[]";
                 }
                 return false;
               });
      //get values for all the filtered objects
      $allFilesValues = array_map(function($obj){ return $obj->value; }, $allFiles);
      return $data['allFiles'];
    }
    

    让我知道这是否适合你。

    【讨论】:

    • 它现在给了我一个不同的错误,“array_map() 期望参数 1 是一个有效的回调,数组必须正好有两个成员”但我会弄清楚的,我明白你现在所说的看看为什么它不起作用,谢谢。
    • 是的,我以错误的顺序将参数传递给了array_map。现在已经编辑了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-04-02
    • 2011-05-06
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多