【问题标题】:Passing input file type via ajax to php is not working通过ajax将输入文件类型传递给php不起作用
【发布时间】:2018-06-29 04:21:49
【问题描述】:

我有这个函数可以从表单中获取值

$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);

var batchid = $("input[name='batchid']").val();
var yrstart = $("input[name='yrstart']").val();
var yrend = $("input[name='yrend']").val();

$.ajax({
    url:"fetch_import.php",
    method:"POST",
    data: { batchid : batchid, yrstart: yrstart, yrend: yrend, fd},
    success: function (data) {
        //show success result div
        if(data)
        {
            showSuccess();
        }
        else
        {
            showFailure();
        }

    },
    error: function () {
        //show failure result div
        showFailure();
        }
}); 
});

还有这样的 php 代码:

enter code here$bcid =  $_POST['batchid'];
$yrs =  $_POST['yrstart'];
$yrg =  $_POST['yrend'];

/* Getting file name */
$filename = $_FILES['file']['name'];

/* Location */
$location = "upload/".$filename;
$FileType = pathinfo($location,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$location);

传递文件不起作用。我已经搜索过这个但仍然不适合我,我想我会理解它是如何工作的。任何想法?泰亚

【问题讨论】:

    标签: php ajax parameter-passing


    【解决方案1】:

    您应该将您的字段附加到fd 并简单地将其用作$.ajax 中的数据参数:

    $("button[name='createimport']").click(function() {
        var fd = new FormData();
        var files = $('#xsfile')[0].files[0];
        fd.append('file',files);
    
        fd.append('batchid', $("input[name='batchid']").val());
        fd.append('yrstart', $("input[name='yrstart']").val());
        fd.append('yrend', $("input[name='yrend']").val());
    
        $.ajax({
            url:"fetch_import.php",
            method:"POST",
            data: fd,
            success: function (data) {
                //show success result div
                if(data)
                {
                    showSuccess();
                }
                else
                {
                    showFailure();
                }
    
            },
            error: function () {
                //show failure result div
                showFailure();
                }
        }); 
    });
    

    【讨论】:

    • 如果我使用该代码,我必须对我的 php 代码进行哪些更改?谢谢! :))
    • 没什么,你的变量应该在$_POST$_FILES
    猜你喜欢
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2012-06-05
    • 2015-01-20
    相关资源
    最近更新 更多