2013-01-16 81 views
0

我想上傳一個文本文件到python腳本。如果我只是上傳表單數據並使用ajax文件上傳與異步

form_contents = $(this).serialize() + "&async=true"; 

然後窗體將停留在網頁上並顯示結果。如果我使用

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

它提交表單和數據文件,但它不留在網頁上。如何添加+ &async=true以使其保留在網頁上。還是有不同的方式來做到這一點?

的住宿網頁上,但不會上傳文件:

  $('#upload').submit(function() { 
     form_contents = $(this).serialize() + "&async=true"; 
     form_action = $(this).attr('action'); 

     $.ajax({ 
     type: 'post', 
      data: formData, 
     url: form_action, 
     success: function (result) { 
     $('#upload').html(result); 
     } 
     }); 
     return false; 
    }); 

不留網頁上,但文件上傳:

$('#upload').submit(function() { 
    var formData = new FormData($('form')[0]); 
    form_action = $(this).attr('action'); 

    $.ajax({ 
    type: 'post', 
    xhr: function() { 
     myXhr = $.ajaxSettings.xhr(); 
     if(myXhr.upload){ 
     myXhr.upload.addEventListener('progress',progressHandlingFunction, false); 
    } 
    return myXhr; 
    }, 
    data: formData, 
    url: form_action, 
    success: function (result) { 
     $('#upload').html(result); 
    } 
    }); 
    return false; 
    }); 

感謝您的幫助,

馬特

+1

把一個'event'參數在您提交功能,並調用'event.preventDefault();'在最頂端該功能,請檢查您的控制檯是否有錯誤。 – Musa

回答

0

您還需要將contentType和processData參數設置爲false。

$('#upload').submit(function() { 
    var formData = new FormData($('form')[0]); 
    form_action = $(this).attr('action'); 

    $.ajax({ 
    type: 'post', 
    xhr: function() { 
     myXhr = $.ajaxSettings.xhr(); 
     if (myXhr.upload) { 
     myXhr.upload.addEventListener('progress', progressHandlingFunction, false); 
     } 
     return myXhr; 
    }, 
    data: formData, 
    url: form_action, 
    processData: false, 
    contentType: false, 
    success: function (result) { 
     $('#upload').html(result); 
    } 
    }); 
    return false; 
}); 

但是,如果發生錯誤,形式將繼續就因爲它從來沒有達到return false;。要停止該操作,以便可以看到該錯誤,請使用event.preventDefault。

$('#upload').submit(function (e) { 
    e.preventDefault(); 
    var formData = new FormData($('form')[0]); 
    form_action = $(this).attr('action'); 

    $.ajax({ 
    type: 'post', 
    xhr: function() { 
     myXhr = $.ajaxSettings.xhr(); 
     if (myXhr.upload) { 
     myXhr.upload.addEventListener('progress', progressHandlingFunction, false); 
     } 
     return myXhr; 
    }, 
    data: formData, 
    url: form_action, 
    processData: false, 
    contentType: false, 
    success: function (result) { 
     $('#upload').html(result); 
    } 
    }); 
}); 
0

難道你不只是簡單地添加一個隱藏的輸入元素的形式?
<input type=hidden name="async" value="true">
......那麼這個值就會自動將您的序列化數據的一部分在formData