Как узнать, работает ли 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 responseText. console.log(xhr.responseText) показывает

response= {"message": "success"}

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

Использование async = false не рекомендуется

Итак, есть ли способ узнать, отправлен ли файл, сохраняя 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")

EDIT:

Я получил эту работу с помощью @FabrícioMatté

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');
          }
       }
    }

Ответы

Ответ 1

Объекты

XMLHttpRequest содержат свойства status и readyState, которые вы можете проверить в событии xhr.onreadystatechange, чтобы проверить, был ли ваш запрос успешным.

Ответ 2

Что-то вроде следующего кода должно выполнить задание:

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState === 4) {
    var response = JSON.parse(xmlhttp.responseText);
      if (xmlhttp.status === 200 && response.status === 'OK') {
         console.log('successful');
      } else {
         console.log('failed');
      }
  }
}