weixin_33675507 2017-03-01 10:40 采纳率: 0%
浏览 26

在Ajax中发送文件和数据

I'm trying to send file and data together to Controller when I send File it work correctly but When I try to send data and file nothing I get.

contentType: false,
processData: false,

and as I remove this codes I can send data what should I do?

html code

<div class="form-group ">
    <input class="form-control" id="title" name="title" type="text" />
</div>
<div class="form-group ">
    <textarea class="form-control" cols="40" id="desc" name="textarea" rows="10"></textarea>
</div>
<div class="form-group ">
    <div class="">
        <div class="radio">
            <label class="radio">
                <input name="answer" id="respawn" type="radio" value="1" /> 1
            </label>
        </div>
        <div class="radio">
            <label class="radio">
                <input name="answer" type="radio" value="2" /> 2
            </label>
        </div>
        <div class="radio">
            <label class="radio">
                <input name="answer" type="radio" value="3" /> 3
            </label>
        </div>
    </div>
</div>
<div class="form-group">
    <input type="file" name="file" id="file">
</div>

controller code

public function create(Request $request)
{
    dd($request->all());

    return response()->json([
        'success' => true,

    ]);
}

ajax code

$("#offer").click(function() {
    var title = $("#title").val();
    var desc = $("#desc").val();
    var respawn = $("#respawn").val();
    var pic = new FormData();
    pic.append('file', $('#file')[0].files[0]);
    var offer = {
        title: title,
        desc: desc,
        respawn: respawn,
        pic: pic
    };
    $.ajax({
        method: 'POST',
        url: '/create',
        headers: {
            'X-CSRF-TOKEN': CSRF_TOKEN
        },
        data: offer,
        contentType: false,
        processData: false,
        success: function(response) {
            alert("Successful!")
        }
    });
});
  • 写回答

1条回答 默认 最新

  • 10.24 2017-03-01 10:48
    关注

    Use the following code:

    $.ajax({
        method:'POST',
        url:'/create',
        headers: {
            'X-CSRF-TOKEN': CSRF_TOKEN
        },
        data:pic,
        contentType: false,
        processData: false,
        success:function(response){
            alert("Successful!")
        }
    });
    

    you were using formData in place of pic.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!