如何在 laravel 控制器中检索 form.serialize() 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43804575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:54:54  来源:igfitidea点击:

how to retrive form.serialize() data in laravel controller

phpajaxlaravel

提问by HirenMangukiya

I use $("form").serialize()to submit form data. while I return value from a method it works fine. My method code is as below.

$("form").serialize()用来提交表单数据。虽然我从一个方法返回值,但它工作正常。我的方法代码如下。

 public function store(Request $request)
 {
    $list = @$request['lists'];
    $total_amount = @$request->total_amount;
    $r_g_amount = @$request->r_g_amount;
    $type = @$request->type;
    $cash = @$request->cash;
    $credit = @$request->credit;
    $bank = @$request->bank;
    $from = @$request->from;
    $to = @$request->to;
    return $cash;
  }

it sends me null value, if I return $request->formdatathen it sends me all details of form. formdatais variable which I pass from ajaxas formdata:$("form").serialize().

它向我发送空值,如果我return $request->formdata然后它向我发送表单的所有详细信息。formdata是我从ajaxas传递的变量formdata:$("form").serialize()

so how can I get values of form data into variable.

那么如何将表单数据的值转换为variable.

ajax request

ajax请求

 $.ajax({
    url: "{{ route('HK.store') }}",
    data: {
       lists: list, total_amount: total_amount, formdata : $("form").serialize(), "_token": "{{ csrf_token() }}"
    },
    type: "POST",
    success: function (data) {
    console.log(data);
    }
 });

enter code here

回答by ismael ansari

Use below code in your controller function of Laravel,

在 Laravel 的控制器功能中使用以下代码,

    $box = $request->all();        
    $myValue=  array();
    parse_str($box['formdata'], $myValue);
    print_r($myValue);

Hope it will help you!

希望它会帮助你!

回答by Alex Slipknot

When you are using dynamic post data you have to be sure that variables exists. So here is an example how to get variables you need:

当您使用动态发布数据时,您必须确保变量存在。所以这里是一个如何获取你需要的变量的例子:

public function store(Request $request)
{
    $data = $request->all();
    $list = array_get($data, 'list', 'default value');
    $total_amount = array_get($data, 'total_amount', 0);
    ...
    return $whatever;
}

回答by AddWeb Solution Pvt Ltd

You need to update your code like:

您需要更新您的代码,例如:

public function store(Request $request)
 {
    $list = $request->lists;
    $total_amount = $request->total_amount;
    $r_g_amount = $request->r_g_amount;
    $type = $request->type;
    $cash = $request->cash;
    $credit = $request->credit;
    $bank = $request->bank;
    $from = $request->from;
    $to = $request->to;

   return response(['cash' => $cash]);
  }