javascript - Ajax 表单提交进度功能失败?

标签 javascript jquery ajax forms

我正在通过 ajax 提交表单并尝试在上传时更新一个简单的进度条。表单提交工作完美,但我无法让进度条更新甚至请求当前加载的数量。

<form enctype="multipart/form-data">          
    <input name="file" type="file" />
    <button>Update Account</button>
</form>
<progress value="0" max="100"></progress>

jQuery + Ajax

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

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

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        xhr: function() {
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){
                myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
            }
            return myXhr;
        },
        async:false,
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
});

提交表单后应运行 addEventListener 以便运行此函数以更新进度:

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $("progress").attr('value', e.loaded);
        $("progress").attr('max', e.total);
    }
}

但是 myXhr.upload.addEventListener(); 中的任何函数似乎都没有运行?

myXhr.upload.addEventListener('progress', alert("test"),  false);

工作正常,但下面没有运行,为什么会这样?:

myXhr.upload.addEventListener('progress', function(){alert("test")},  false);

这个例子使用了类似的编码:

http://www.matlus.com/html5-file-upload-with-progress/

最佳答案

$(document).live("submit", "form", function(){

应该是:

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

或者更好:

$("#static-container-Id").on("submit", "form", function(){

如果你想使用live (jQuery < 1.4.4)

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

关于javascript - Ajax 表单提交进度功能失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10901262/

相关文章:

javascript - 异步 xml 加载并在 html 中分页显示

javascript - 使用ajax插入查询而不重新加载整个页面

javascript - 脚本标记上的 defer 属性使我的脚本太长而无法加载

javascript - 复选框更改在 html 表和 jquery 内部无法正常工作

javascript - 如何使用 jQuery 在文本中插入超链接?

javascript - 如何将复选框值作为数组?

javascript - 使用 ajax 从嵌套的 .json 调用数据

javascript - 使用 lambda 修改值

javascript - 为什么插件 jQuery AJAX 选择器不起作用?

javascript - 如何在 Symfony 3 中获取 ajax 请求的 post 参数