ajax上传图片没有刷新,如何得到一个错误,如果什么时候错了

ajax upload picture without refresh, How to get back an error if something when wrong

本文关键字:一个 错了 什么时候 如果 错误 何得 刷新 ajax      更新时间:2023-09-26

我使用Ajax上传图片而不刷新。但是由于某些原因,诸如文件太大之类的错误消息不会显示出来。如果一切顺利,没有错误,一切正常,我得到一个消息,说它工作。我尝试了以下两种方法:

form_data.append('file', file_data);
$.ajax({
            url: 'upload.php',
            dataType: 'json', 
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         
            type: 'post',
            success: function(response){
                if (response.errors == 0){
                     //do something to show it went well
                }
                else{
                     //do something to show it went wrong
                }
           }

然后过了一段时间,我意识到上面可能是错误的,因为它只在上传成功时起作用。所以我试着这样做:

            success: function(response){
                //do something to show it went well
           },
           error: function(response){
                //do something to show it went wrong
                }

但是这也不行

上传图片的脚本如下:

   if ($_FILES["file"]["size"] > 5000000) {
        echo json_encode(array('errors'=>1,'naam_orgineel'=>$_FILES['file']['name'], 'errormsg'=>'file size is to big'));
        $$errors = 1;
    }
   if ($errors == 0){
   move_uploaded_file($_FILES['file']['tmp_name'], $target);
   echo json_encode(array('errors'=>0,'naam_orgineel'=>$_FILES['file']     ['name'], 'naam'=>$target_file));
   }

有人知道为什么错误信息不以两种方式显示吗?

尝试响应失败

var request = $.ajax({
  ......
});
request.done(function( msg ) {
  ....
});
request.fail(function( jqXHR, textStatus ) {
  alert( "Request failed: " + textStatus );
});
相关文章: