как узнать работает ли XMLHttpRequest.send ()

я используюXMLHttpRequest отправить файл изjavascript код дляdjango viewМне нужно определить, был ли файл отправлен или произошла какая-то ошибка. Я использовал jquery для написания следующего javascript.

В идеале я хотел бы показать пользователю сообщение об ошибке, что файл не был загружен. Есть ли способ сделать это вjavascript?

Я пытался сделать это, возвращаяsuccess/failure Сообщение отdjango view , положивsuccess/failed message какjson и отправив обратно сериализованный JSON изdjango view. Для этого я сделалxhr.open() non-asynchronous, Я пытался напечататьxmlhttpRequest Объект & APOS; sresponseText .Отельconsole.log(xhr.responseText)  шоу

response= {"message": "success"}

Что меня интересует, так это правильный ли способ сделать это. Во многих статьях я обнаружил предупреждение, что

Using async=false is not recommended

Итак, есть ли способ узнать, был ли файл отправлен, сохраняяxhr.open() асинхронный?

$(document).ready(function(){
   $(document).on('change', '#fselect', function(e){
            e.preventDefault();
            sendFile();
        });
});

function sendFile(){
   var form = $('#fileform').get(0);
   var formData = new FormData(form);
   var file = $('#fselect').get(0).files[0];
   var xhr = new XMLHttpRequest();
   formData.append('myfile', file);
   xhr.open('POST', 'uploadfile/', false);
   xhr.send(formData);
   console.log('response=',xhr.responseText);
}

мойdjango просмотр извлекает файл из данных формы и записывает в папку назначения.

def store_uploaded_file(request):
   message='failed'
   to_return = {}
   if  (request.method == 'POST'):          
      if request.FILES.has_key('myfile'):
         file = request.FILES['myfile']
         with open('/uploadpath/%s' % file.name, 'wb+') as dest:
            for chunk in file.chunks():
               dest.write(chunk)
               message="success"
   to_return['message']= message
   serialized = simplejson.dumps(to_return)
   if store_message == "success":
      return HttpResponse(serialized, mimetype="application/json")
   else:
      return HttpResponseServerError(serialized, mimetype="application/json")

РЕДАКТИРОВАТЬ:

Я получил это с помощью @ Fabr & # xED; cioMatt & # xE9;

xhr.onreadystatechange=function(){
       if (xhr.readyState==4 && xhr.status==200){
          console.log('xhr.readyState=',xhr.readyState);
          console.log('xhr.status=',xhr.status);
          console.log('response=',xhr.responseText);

          var data = $.parseJSON(xhr.responseText);
          var uploadResult = data['message']
          console.log('uploadResult=',uploadResult);

          if (uploadResult=='failure'){
             console.log('failed to upload file');
             displayError('failed to upload');
          }else if (uploadResult=='success'){
             console.log('successfully uploaded file');
          }
       }
    }

Ответы на вопрос(2)

Ваш ответ на вопрос