【问题标题】:HTML file upload with jQuery/Ajax not working使用 jQuery/Ajax 上传 HTML 文件不起作用
【发布时间】:2012-07-29 07:03:00
【问题描述】:

我正在尝试合并来自 Stack 用户 DannYo 的 comment here 的一些代码,但是我的他的代码版本似乎无法运行。错误和“beforesend”函数每次都返回。

HTML

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" id="file">
    <input type="email" id="sender" name="sender" required>
    <input type="email" id="receiver" name="receiver" required>
    <input type="text" id="message" name="message">
    <button id="send" class="button">Send it</button>
</form>

JavaScript

$("form").on("submit", function() {

    var formData = new FormData($('form')[0]);

    $.ajax({
        url: 'upload.php',  //server script to process data
        type: 'POST',
        xhr: function() {  // custom xhr

            myXhr = $.ajaxSettings.xhr();

            if (myXhr.upload) { // check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
            }

            return myXhr;

        },

        //Ajax events
        beforeSend: function() { console.log("before send function works"); },
        success: function(e) {
            console.log(e);
        },
        error: function() { console.log("error function works"); },

        // Form data
        data: formData,

        //Options to tell JQuery not to process data or worry about content-type
        cache: false,
        contentType: false,
        processData: false
    });

    return false;

});

PHP

出于测试目的,upload.php 文件只有&lt;?php echo "success"; ?&gt;

使用 Chrome 的网络开发人员工具,我没有看到我的文件被传输到任何地方。有人在我的代码中看到一个明显的漏洞吗?谢谢

【问题讨论】:

  • The error and the "beforesend" functions return each time.你报什么错误?
  • 控制台日志只打印我在错误函数中指定的内容:“错误函数有效”

标签: jquery ajax file file-upload upload


【解决方案1】:

如果您的错误函数被调用,那么答案很可能在其结果中。请检查显示 error function works 时返回的错误是什么。

error: function(xhr, status, error) {
    alert(xhr.responseText);
    // OR
    alert(status + " : " + error);
}

编辑:还要注意,我相信您需要处理您尝试上传的文件的保存。 This tutorial for uploading files in php 可能有用。

【讨论】:

  • 我同意我的错误函数很愚蠢。使用你给我的,它只是刷新页面,但在控制台中显示之前不会:Uncaught TypeError: Cannot ready property 'Message' of undefined
  • @muppethead 这很有趣。我已经用我之前做过的其他事情更新了我的答案。
  • 啊哈!是的,您的编辑被证明是有帮助的。错误提示 progressHandlingFunction 未定义。所以,我添加了进度处理函数,现在表单不返回错误函数。但相反,我收到 500 内部服务器错误。那是因为我在本地使用 MAMP 工作吗?
  • 其实,算了。我的 php 文件错误地注释掉了导致 500 ISE 的文本。现在一切正常。感谢您的帮助乔希
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多