【问题标题】:How to get formdata values sent by ajax post method in laravel controller如何在laravel控制器中获取ajax post方法发送的formdata值
【发布时间】:2016-04-18 10:58:16
【问题描述】:

我正在尝试使用 formdata 通过 ajax 发送一组数据,包括图像文件,但是当我想在 laravel 控制器中访问该数据时,它显示一个空白数组。

这是我的 ajax 代码 -

var fd = new FormData();
    fd.append("photo",files[0]);
    fd.append("user_id",localStorage.getItem('userId'));
    fd.append("doctype","dl_image");       
    console.log(fd);



   //ajax code
    $http.post('uploadfile', fd, {    
            withCredentials: true,      
            headers: { 'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content') }       
     }).success(function(data, status) {        

               console.log(data);


     });

PHP 代码 -

    $data = Request::all();
    $photo = Request::file('photo');
    $userid = Request::get('user_id');
    $doctype = Request::get('doctype');


    $postData = array(
        'photo' => $photo,
        'user_id' => $userid,
        'doctype' => $doctype  
    );
    var_dump($data);
    die();

当数据转储到浏览器的控制台时,它会显示

array(0) {
}

需要帮助。

【问题讨论】:

  • 请注意,Angular 5+ 的 HttpClient 会在检测到正在发送的 FormData() 对象时自动将内容类型设置为 FormData。

标签: php angularjs ajax laravel controller


【解决方案1】:

AngularJS 默认发送带有application/json 类型和JSON 正文的POST 请求。
所以我认为你需要使用:

headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
data: $.param(data)

ajax 代码中。
您可能需要使用 $name = Input::get('name'); 之类的东西,而不是 $userid = Request::get('user_id');

【讨论】:

  • 接受文件?我没找到你
【解决方案2】:

使用FormData API POST 文件和数据时,将Content-Type header 设置为undefined 很重要。

试试:headers: { 'Content-Type': undefined }

【讨论】:

    【解决方案3】:

    请尝试jquery的序列化方法。

    function myForm( form ){
        var formData = $(form).serialize();
        att=form.attr("action") ;
        $.post(att, formData).done(function(data){
            alert(data);
        });
        return true;
    }
    

    【讨论】:

    • 我正在使用 angularJs
    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多