【问题标题】:Why do I hit error in AJAX file upload with jQuery?为什么我在使用 jQuery 上传 AJAX 文件时遇到错误?
【发布时间】:2014-10-14 21:15:36
【问题描述】:

我正在使用 HTML5 的 FormData 和 jQuery 开发多文件上传器。我有以下代码:

$(function() {
    $('#file').bind("change", function() {
        var formData = new FormData();
        //loop for add $_FILES["upload"+i] to formData
        for (var i = 0, len = document.getElementById('file').files.length; i < len; i++) {
            formData.append("file" + i, document.getElementById('file').files[i]);
        }

        //send formData to server-side
        $.ajax({
            url : "file-upload.php",
            type : 'post',
            data : formData,
            dataType : 'json',
            async : true,
            processData: false,  // tell jQuery not to process the data
            contentType: false,   // tell jQuery not to set contentType
            error : function(request) {
                alert('error!!');
                console.log(request.responseText);
            },
            success : function(json) {
                alert('success!!');
                $('#upload-result')[0].append(json);
            }
        });
    });
});

我可以看到我的file-upload.php 工作正常,因为文件已上传!但是为什么我的jQuery点击了错误函数而不是成功函数?我收到错误警报。

在控制台窗口中,我看到了我的 PHP echo 调用的结果!我想将其附加到#upload-result,如我的成功函数所示。

PHP 代码

foreach($_FILES as $index => $file)
{
    $fileName     = $file['name'];
    // echo '[ file name: ' . $fileName . ' - ';
    $fileTempName = $file['tmp_name'];
    // echo 'file temp name: ' . $fileTempName . ' ]';

    if(!empty($file['error'][$index]))
    {
        // some error occured with the file in index $index
        // yield an error here
        return false; // return false also immediately perhaps??
    }

    // check whether it's not empty, and whether it indeed is an uploaded file
    if(!empty($fileTempName) && is_uploaded_file($fileTempName))
    {
        // the path to the actual uploaded file is in $_FILES[ 'file' ][ 'tmp_name' ][ $index ]
        // do something with it:
        move_uploaded_file($fileTempName, "uploads/" . $fileName);
        echo json_encode('<p>Click <a href="'. 'uploads/' . $fileName . '">here</a> to download file!</p>');
    }
}

【问题讨论】:

  • 你能说明错误是什么吗?
  • 查看浏览器的开发者工具。重新加载页面。 JavaScript 控制台说什么?您能在 Net 选项卡中看到您的 Ajax 请求吗?格式是否正确?它得到回应了吗?回答正确吗?
  • 可以打印request.responseText
  • jQuery错误函数的定义为:Function( jqXHR jqXHR, String textStatus, String errorThrown )看第三个参数,jQuery报什么错误?
  • 使用控制台输出更新问题。

标签: php jquery ajax file-upload multipartform-data


【解决方案1】:

我想通了。我收到了 jQuery AJAX 错误,即使我的 php 文件的状态代码是 200因为我的 dataType 是 JSON,而我正在返回简单的 HTML。

dataType: 'html',

修好了!

谢谢大家。

【讨论】:

    猜你喜欢
    • 2021-03-10
    • 1970-01-01
    • 2016-12-27
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 2016-07-10
    相关资源
    最近更新 更多