douxu0550 2015-11-17 15:59
浏览 278
已采纳

通过ajax post将文件与表单数据一起发送

I'm trying to upload a file via ajax together with some fields in a form. However, it doesn't work. I get this error.

Undefined Index :- File

Here's my code.

HTML

    <!-- File Button --> 
    <div class="form-group">
    <label class="col-md-4 control-label" for="file">Upload Software / File</label>
    <div class="col-md-4">
    <input id="file" name="file" class="input-file" type="file">
    </div>
    </div>

<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>  
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required=""> 
</div>
</div>

Ajax

$("#add_product").click(function(e){
    e.preventDefault();
    product_name = $("product_name").val();
    //d = $("#add_new_product").serialize();
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: $("#add_new_product").serialize(),
        success: function(response)
        {
            //
            alert(response);

        }
    })
});

PHP

if (0 < $_FILES['file']['error']) 
{
 echo ":!";
}
else 
{
echo "ASa";
}

What am I missing here?

  • 写回答

3条回答 默认 最新

  • doulu4534 2015-12-03 16:46
    关注

    Can you try using FormData():

    $("form#files").submit(function(){
    
        var formData = new FormData($(this)[0]);
    
        $.ajax({
            url: window.location.pathname,
            type: 'POST',
            data: formData,
            async: false,
            success: function (data) {
                alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
        });
    
        return false;
    });
    

    The above is a sample code, but you may use it to modify it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛