检测ajax上传何时意外终止


detect when ajax upload is unexpectedly terminated

我有这个ajax上传代码,它发送数据返回,说明上传是否成功。但是,它只知道文件是否没有错误,并在文件上传后移动到目标路径,如果上传在完成之前终止,则不会返回任何数据。是否有一种方法可以检测上传意外终止的时刻并提醒页面?

$('#send').click(function() {
 var fileInput = $('#file')[0];
     var data = new FormData();
  for(var i = 0; i < fileInput.files.length; ++i){     
      data.append('file[]',fileInput.files[i]);
   }
     $.ajax({
    type:'POST',
    method:'POST',
    url:'upload.php',
    headers:{'Cache-Control':'no-cache'},
    data:data,
    contentType:false,
    processData:false,
    success: function(response){
        var return_data = response;
        if(return_data !== 'success') {
        $('#status').html('uploaded'); 
        }
        else if(return_data == 'success') {
           $('#status').html('upload failed'); 
        }         
      }
   });
});

and in upload.php:

if($_FILES['file']['error'][$key] == 0
   && move_uploaded_file($_FILES['file']['tmp_name'][$key],"video/test/$name")){
        echo "success";
 }else{
        echo "failed";

$.ajax选项对象添加一个error方法

$('#send').click(function() {
   var fileInput = $('#file')[0];
   var data = new FormData();
   for(var i = 0; i < fileInput.files.length; ++i){     
       data.append('file[]',fileInput.files[i]);
   }
   $.ajax({
        type:'POST',
        method:'POST',
        url:'upload.php',
        headers:{'Cache-Control':'no-cache'},
        data:data,
        contentType:false,
        processData:false,
        beforeSend: function(response){
            // before send do some func if u want
        },
        success: function(response){
            var return_data = response;
            if(return_data !== 'success') {
               $('#status').html('uploaded'); 
            } else if(return_data == 'success') {
               $('#status').html('upload failed'); 
            }         
        },
        complete: function(response){
            // do some func after complete if u want
        },
        error: function(response){
            // here is what u want
            alert ("Error: " + response.statusText);
        },
    });
    // end ajax call
});

$的参数之一。Ajax错误。如果页面没有返回状态200,可以指定一个函数来运行。

从jquery文档(http://api.jquery.com/jQuery.ajax/)

"错误类型:函数(jqXHR, jqXHR,字符串textStatus,字符串errorThrown)请求失败时调用的函数。该函数接收三个参数:jqXHR(在jQuery 1.4中)。x, XMLHttpRequest)对象,一个描述发生的错误类型的字符串和一个可选的异常对象(如果发生了)。第二个参数的可能值(除了null)是"timeout", "error", "abort"answers"parsererror"。当发生HTTP错误时,errorThrown接收HTTP状态的文本部分,例如"Not Found"或"Internal Server error"。从jQuery 1.5开始,错误设置可以接受一个函数数组。每个函数将依次调用。注意:这个处理程序不会被跨域脚本和JSONP请求调用。这是一个Ajax事件。"