Javascript 如何确定 XMLHttpRequest.send() 是否有效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10876123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:22:36  来源:igfitidea点击:

how to find out if XMLHttpRequest.send() worked

javascriptxmlhttprequest

提问by damon

I am using XMLHttpRequestto send a file from javascriptcode to a django view.I need to detect,whether the file has been sent or if some error occurred.I used jquery to write the following javascript.

我正在使用XMLHttpRequest将文件从javascript代码发送到一个django view。我需要检测文件是否已发送或是否发生了某些错误。我使用 jquery 编写了以下 javascript。

Ideally I would like to show the user an error message that the file was not uploaded.Is there some way to do this in javascript?

理想情况下,我想向用户显示文件未上传的错误消息。有什么方法可以做到这一点javascript吗?

I tried to do this by returning a success/failuremessage from django view, putting the success/failed messageas jsonand sending back the serialized json from the django view.For this,I made the xhr.open()non-asynchronous. I tried to print the xmlhttpRequestobject's responseText.The console.log(xhr.responseText)shows

我试图返回一个做到这一点success/failure的消息django view,把success/failed messagejson从发回的序列化JSON django view。为此,我做了xhr.open()non-asynchronous。我试图打印xmlhttpRequest对象的responseText.Theconsole.log(xhr.responseText)显示

response= {"message": "success"}

What I am wondering is,whether this is the proper way to do this.In many articles,I found the warning that

我想知道的是,这是否是执行此操作的正确方法。在许多文章中,我发现警告

Using async=false is not recommended

不推荐使用 async=false

So,is there any way to find out whether the file has been sent,while keeping xhr.open()asynchronous?

那么,有没有办法在保持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);
}

My djangoview extracts file from form data and writes to a destination folder.

我的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:

编辑:

I got this working with the help of @FabrícioMatté

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

采纳答案by Fabrício Matté

XMLHttpRequestobjects contain the statusand readyStateproperties, which you can test in the xhr.onreadystatechangeevent to check if your request was successful.

XMLHttpRequest对象包含statusreadyState属性,您可以在xhr.onreadystatechange事件中测试这些属性以检查您的请求是否成功。

回答by Nima

Something like the following code should do the job:

类似下面的代码应该可以完成这项工作:

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

回答by lwairore

XMLHttpRequestprovides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.

XMLHttpRequest提供侦听在处理请求时可能发生的各种事件的能力。这包括定期进度通知、错误通知等。

So:

所以:

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.addEventListener("load", transferComplete);
   xhr.addEventListener("error", transferFailed);
  }

    function transferComplete(evt) {
        console.log("The transfer is complete.");
        // Do something
    }

    function transferFailed(evt) {
        console.log("An error occurred while transferring the file.");
        // Do something
    }

You can read more about Using XMLHttpRequest.

您可以阅读有关使用 XMLHttpRequest 的更多信息。