简体   繁体   English

Laravel Ajax Input :: all()通过FormData发送时返回空

[英]Laravel Ajax Input::all() return empty when send it via FormData

im building an application with Laravel 4, in some point i want to add some model throught modal(Bootstrap) so i needed ajax to send my from, i have setup my route and action in controller, and then i have built the form markup with blade, i have wrote the ajax code, the request goes fine and i retrieve the inputs through Input facade, the problem here is that form has a file input, and when serialising form data with $('#formRub ').serialize(), it can't handle the file input, so i have to use FromData object and set the processData and contentType to false in the ajax request, the request sent, but i when u access to Input facade i got empty array !! 我用Laravel 4构建了一个应用程序,在某种程度上,我想通过modal(Bootstrap)添加一些模型,所以我需要ajax来发送我的信息,我在控制器中设置了路线和动作,然后用刀片,我已经编写了ajax代码,请求正常,我通过Input Facade检索了输入,这里的问题是表单具有文件输入,并且使用$('#formRub').serialize()序列化表单数据时,它无法处理文件输入,因此我必须使用FromData对象并将ajax请求(已发送请求)中的processData和contentType设置为false,但是当我访问Input Facade时,我得到了空数组!

Route : 路线:

Route::post('/add', ['as' => 'rubrique.add.post', 'uses' => 'RubriquesController@ajaxaddpost']);

Controller : 控制器:

class RubriquesController extends \BaseController {


public function ajaxaddpost(){
  return  dd(Input::all());
    $v = Validator::make(Input::all(), Rubrique::$rules);
    if($v->fails()){
        return Response::json([
            'fail' => true,
            'errors' => $v->errors()->toArray()
        ]);
    }
    if(Input::hasFile('image'))
        return Response::json(['success' => Input::file('image')]);

    return Response::json(['fail' => 400]);
}

Markup : 标记:

         {{ Form::open(['route' => 'rubrique.add.post', 'method' => 'post', 'files' => true, 'class' => 'form-horizontal', 'id' => 'rubForm']) }}
                {{Form::label('name', 'Nom de la boutique :', ['class' => 'col-md-4 control-label'])}}
                    {{Form::text('name', null, ['class' => 'form-control', 'placeholder' => 'Entrer votre nom de boutique..'])}}

                {{Form::label('desc', 'Description :', ['class' => 'col-md-4 control-label'])}}
                    {{Form::textarea('desc', null, ['class' => 'form-control', 'placeholder' => 'Enter votre e-mail..', 'rows' => '3'])}}



                {{Form::label('image', 'Image :', ['class' => 'col-md-4 control-label'])}}
                    {{Form::file('image', ['class' => 'form-control', 'placeholder' => 'Enter votre e-mail..'])}}

                {{Form::label('rubrique_id', 'Rubrique Parent :', ['class' => 'col-md-4 control-label'])}}
                    {{ Form::rubriques(0) }}

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                {{Form::submit('Ajouter', ['class' => 'btn btn-primary', 'id' => 'sendRubrique']) }}

            </div>
        </div>
        {{Form::close()}}

JS: JS:

        $('#rubForm').submit(function(e){
            e.preventDefault();
            var $form = $( this ),
                dataFrom = new FormData($form),
                url = $form.attr( "action"),
                method = $form.attr( "method" );

            $.ajax({
                url: url,
                data: dataFrom,
                type: method,
                contentType: false,
                processData: false
            });
        });

The key are in your ajax request. 密钥在您的ajax请求中。 In the controller you can do whatever you want. 在控制器中,您可以做任何您想做的事情。

var form = document.forms.namedItem("yourformname"); // high importance!, here you need change "yourformname" with the name of your form
var formdata = new FormData(form); // high importance!

$.ajax({
    async: true,
    type: "POST",
    dataType: "json", // or html if you want...
    contentType: false, // high importance!
    url: '{{ action('yourController@postMethod') }}', // you need change it.
    data: formdata, // high importance!
    processData: false, // high importance!
    success: function (data) {

        //do thing with data....

    },
    timeout: 10000
});

Your JavaScript should look like this: 您的JavaScript应该如下所示:

$('#rubForm').submit(function(e){
    e.preventDefault();
    var $form = $( this ),
        dataFrom = $form.serialize(),
        url = $form.attr( "action"),
        method = $form.attr( "method" );

    $.ajax({
        url: url,
        data: dataFrom,
        type: method,
        processData: false
    });
});

You should use $form.serialize() and you have to remove contentType: false, 您应该使用$form.serialize()并且必须删除contentType: false,

Now if you put into your controller for example something like this: 现在,例如,将诸如此类的内容放入控制器中:

file_put_contents("test.txt", var_export(Input::all(), true));

it will create file with data in it however I don't know if it will work for file input 它会创建包含数据的文件,但是我不知道它是否可以用于文件输入

EDIT 编辑

I didn't notice seralize() and file input in the question, so now, you should add name attribute to your form: 我没有在问题中注意到seralize()和文件输入,因此现在,您应该在表单中添加name属性:

 {{ Form::open(['route' => 'rubrique.add.post', 'method' => 'post', 'files' => true, 'class' => 'form-horizontal', 'id' => 'rubForm', 'name' =>'myform']) }}

and use the following code: 并使用以下代码:

$('#rubForm').submit(function(e){
    e.preventDefault();
    var $form = $( this ),

        dataFrom = new FormData(document.forms.namedItem("myform"));
        url = $form.attr( "action"),
        method = $form.attr( "method" );

    $.ajax({
        url: url,
        data: dataFrom,
        type: method,
        processData: false
    });
});

那是因为发送带有“ data”的数组,与jquery ajax一样, Input::all()显示[data]='_token=d76as78d6as87d6a&data1=value1等...如果不是,则作为秒表请求您打印值Input::all将显示一个完整的数组,laravel以不同的方式处理jQuery发送的POST请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM