使用AJAX以相同的形式上传数据和文件

时间:2015-11-16 12:58:47

标签: jquery ajax forms file-upload

我有一个表格可以选择,复选框和文件上传。下面的代码适用于数据,但是当我在目标php文件中打印“$ _FILES”时,它给了我一个空数组。以下代码仅适用于数据:

$('form.ajax').on('submit', function () {
    event.preventDefault();

    // Update button text.
    var uploadButton = document.getElementById('submit');
    uploadButton.innerHTML = 'Uploading...';
    var that = $(this),
        url = that.attr('action'),
        type = that.attr('method'),
        data = {}

    that.find('[name]').each(function (index, value) {
        var that = $(this),
            name = that.attr('name'),
            value = that.val();

        data[name] = value;
    });

    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function (response) {
            console.log(response);
        }
    });
    return false;
});

下一部分仅适用于文件:

$('form.ajax').on('submit', function () {
    event.preventDefault();

    // Update button text.
    var uploadButton = document.getElementById('submit');
    uploadButton.innerHTML = 'Uploading...';

    var that = $(this),
        url = that.attr('action'),
        type = that.attr('method'),
        data = new FormData();
    var element = document.getElementById("fileupload");
    var myfiles = element.files;
    var data = new FormData();
    var i = 0;
    for (i = 0; i < myfiles.length; i++) {
        data.append('file' + i, myfiles[i]);
    }

    $.ajax({
        url: url,
        type: type,
        contentType: false,
        data: data,
        cache: false,
        processData: false,
        success: function (response) {
            console.log(response);
        }
    });
    return false;
});

对于我注意到的行contentType: falseprocessData: false似乎使$ _POST数组返回空。有没有办法结合使用相同的代码来获取$ _POST中的数据和$ _FILES中的文件?

由于

0 个答案:

没有答案