Jquery,ajax之前发送不起作用

时间:2013-04-06 15:21:45

标签: jquery ajax file upload progress

这些是照片上传代码:

$.ajax({
    url: "php/uploadPhoto.php",
    type: "POST",
    data: formdata,
    processData: false,
    contentType: false,
    beforeSend: function(XMLHttpRequest){
        XMLHttpRequest.upload.addEventListener("progress", function(evt){
            if(evt.lengthComputable){
                var percentComplete = evt.loaded / evt.total;
                alert(percentComplete);
            }
        }, false);
    },
    success: function (res) {

    }
});

如果我不添加“beforeSend”部分,它会起作用....

1 个答案:

答案 0 :(得分:1)

试试这个:

$.ajax({
    url: "",
    data: formdata,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    xhr: function() {
        var myXhr = $.ajaxSettings.xhr();
        if (myXhr.upload) {
            if (myXhr.upload.addEventListener) {
                myXhr.upload.addEventListener('progress', `YOUR CALLBACK`, false);
            } else if(myXhr.upload.attachEvent) {
                myXhr.upload.attachEvent('progress', `YOUR CALLBACK`);
            }
        }
        return myXhr;
    },
    success: function (data) { },
    error: function (jqXHR, textStatus, errorThrown) { }
});