如何在jquery中修复ajax xhr错误

时间:2016-09-10 08:35:30

标签: javascript jquery ajax

基本上我有type="file",我需要通过Ajax发送所选文件,但是每次表单提交时我都会收到一个控制台错误,上面写着:

Error while submitting ajax

这是我提交myform的方式:

$(document).ready(function() {
$('form').submit(function(event) {
    event.preventDefault();
    checkforImage($('#Propicselecter_file'), "yes");
});
$('[type="file"]').change(function() {
    var fileInput = $(this);
    checkforImage(fileInput, "no");
});
});

function submit_form(){
var fileInput = $('#Propicselecter_file');
$.ajax({
        url: '../propicuploader',
        type: 'POST',
        processData: false,
        data: fileInput[0],
        success: function(data){
        }
    });
}

function checkforImage(fileInput, submitornot){
if (fileInput.length && fileInput[0].files && fileInput[0].files.length) {
    var url = window.URL || window.webkitURL;
    var image = new Image();
    image.onload = function() {
      $("#NotPictureerror_spn").text("");
      if(submitornot == "yes"){
        submit_form();

      }
    };
    image.onerror = function() {
      $("#NotPictureerror_spn").text("Chosen file is not an image, Please Try Again");
    };
    image.src = url.createObjectURL(fileInput[0].files[0]);
}
}

提前致谢:)

1 个答案:

答案 0 :(得分:1)

尝试传递formData对象而不是文件对象:

var form_data = new FormData();
form_data.append('file', fileInput.files[0]);
$.ajax({
     url: '../propicuploader',
     type: 'POST',
     processData: false,
     contentType:false, // Added
     data: form_data,
     success: function(data){
   }
});