how to find out if XMLHttpRequest.send() worked

前端 未结 3 1811
小蘑菇
小蘑菇 2020-12-05 10:19

I am using XMLHttpRequest to send a file from javascript code to a django view.I need to detect,whether the file has been sent or if s

相关标签:
3条回答
  • 2020-12-05 10:58

    XMLHttpRequest provides 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.

    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.

    0 讨论(0)
  • 2020-12-05 11:02

    XMLHttpRequest objects contain the status and readyState properties, which you can test in the xhr.onreadystatechange event to check if your request was successful.

    0 讨论(0)
  • 2020-12-05 11:02

    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');
              }
          }
        }
    
    0 讨论(0)
提交回复
热议问题