[Turn] In-depth understanding of the fifth part of the ajax series - progress events

    Typically, the completion of an HTTP request is detected using the readystatechange event . The XHR2 draft specification defines the Progress Events specification, the XMLHttpRequest object triggers different types of events at different stages of the request, so it no longer needs to check the readyState property. This draft defines events related to client-server communication. These events were originally only for XHR operations, but they are also borrowed by other APIs (such as the File API). This article will detail progress events

 

Base

  There are the following 6 progress events

  loadstart : fires when the first byte of response data is received

  progress : touch continuously while receiving the response

  error : fires when an error occurs in the request

  abort : Fired when the connection is terminated due to a call to the abort() method

  load : fires when the complete response data is received

  loadend : Fired after communication is complete or after an error, abort or load event is fired

  timeout : Triggered when a timeout occurs

  [Note] IE9-browser does not support the above events (IE9 browser only supports the load event)

  Each request starts by firing the loadstart event , then, usually every 50 milliseconds or so, fires the progress event , then fires  one of the load , error , abort  , or  timeout  events, and ends with firing the loadend event

  For any specific request, the browser will only fire one of the load, abort, timeout and error events. The draft XHR2 specification states that the browser should fire the loadend event once one of these events occurs

 

load

  The load event is fired when the response is received, so there is no need to check the readyState property. But a completed request is not necessarily a successful request. For example, the handler for the load event should check the status code of the XMLHttpRequest object to determine that it received a "200 OK" rather than a "404 Not Found" HTTP response.

copy code
<button id="btn">Get information</button>
<div id="result"></div>
<script>
btn.onclick = function(){
    //create xhr object
    var xhr;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    // progress event
    xhr.onload = function(){
        if(xhr.status == 200){
            result.innerHTML += xhr.responseText;
        }
    }
    //send request
    xhr.open('get','message.xml',true);
    xhr.send();
}
</script>        
copy code

 

progress

  The progress event fires periodically as the browser receives new data. The onprogress event handler receives an event object whose target property is the XHR object , but contains three additional properties : lengthComputable , loaded and total . Among them, lengthComputable is a boolean value indicating whether progress information is available , loaded indicates the number of bytes received , and total indicates the expected number of bytes according to the Content-Length response header . With this information, it's time to create a progress indicator for the user

copy code
<button id="btn">Get information</button>
<div id="result"></div>
<div id="music"></div>
<script>
btn.onclick = function(){
    //create xhr object
    var xhr;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    // progress event
    xhr.onprogress = function(e){
        e = e || event;
        if (e.lengthComputable){
            result.innerHTML = "Received " + e.loaded + " of " + e.total + " bytes";
        }
    };
    xhr.onload = function(e){
        var data = xhr.response;
        e = e || event;
        if(xhr.status == 200){
            var audio = document.createElement('audio');
            audio.onload = function(){
                URL.revokeObjectURL(audio.src);
            }
            audio.src = URL.createObjectURL(data);
             console.log(audio);
            audio.setAttribute('controls','');
            if(!music.innerHTML){
                music.appendChild(audio);
            }
        }
    };
    //send request
    xhr.open('get','myocean.mp3',true);
    xhr.responseType = 'blob';
    xhr.send();
}
</script>    
copy code

 

Upload progress

  In addition to these useful events defined for monitoring HTTP response loading, XHR2 also provides events for monitoring HTTP request uploading. In browsers that implement these features, the XMLHttpRequest object will have the upload attribute . The upload property value is an object that defines the addEventListener() method and the entire progress event collection, such as onprogress and onload (but the upload object does not define the onreadystatechange property, upload can only trigger new event types)

  The upload event handler can be used just like the normal progress event handler. For XMLHttpRequest objects, set XHR.onprogress to monitor the download progress of the response , and set XHR.upload.onprogress to monitor the upload progress of the request

copy code
<input type="file" name="file1" id="file1" style="display:none">
<button id="btn">Upload file</button>
<div id="pro"></div>
<div id="result"></div>
<script>
btn.onclick = function(){
    file1.click();
    pro.innerHTML = result.innerHTML = '';
}
file1.onchange = function(){
    //create xhr object
    var xhr;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    var data = file1.files [0];
    //upload event
    xhr.upload.onprogress = function(e){
        e = e || event;
        if (e.lengthComputable){
            pro.innerHTML = "Upload progress is: " + e.loaded + " of " + e.total + " bytes" + '; percentage is: ' + e.loaded/e.total;
        }
    }
    xhr.onload = function(e){
        var data = xhr.responseText;
        e = e || event;
        if(xhr.status == 200){
            result.innerHTML =  data;
        }
    };
    //send request
    xhr.open('post','pp.php',true);
    xhr.setRequestHeader("content-type",data.type);
    xhr.send(data);
}
</script>      
copy code
copy code
<?php
error_reporting(E_ALL & ~E_NOTICE);
touch($file);
if(preg_match('/image/',apache_request_headers()['content-type'])){
    $file = 'photo/test.jpg';
    binary_to_file($file);
    echo 'File upload successfully!';
}else{
    echo 'The file format is incorrect, please select a picture file';
}
function binary_to_file($file){
    $content = $GLOBALS['HTTP_RAW_POST_DATA']; // requires php.ini settings
    if(empty($content)){
        $content = file_get_contents('php://input'); //No need for php.ini settings, low memory pressure
    }
    $ret = file_put_contents($file, $content, true);
    return $ret;
};
?>
copy code

 

其他事件

  HTTP请求无法完成有3种情况,对应3种事件。如果请求超时,会触发timeout事件。如果请求中止,会触发abort事件。最后,像太多重定向这样的网络错误会阻止请求完成,但这些情况发生时会触发error事件

  可以通过调用XMLHttpRequest对象abort()方法取消正在进行HTTP请求。调用abort()方法在这个对象上触发abort事件

  调用abort()的主要原因是完成取消或超时请求消耗的时间太长或当响应变得无关时。假如使用XMLHttpRequest为文本输入域请求自动完成推荐。如果用户在服务器的建议达到之前输入了新字符,这时等待请求不再有用,应该中止

  XHR对象的timeout属性等于一个整数,表示多少毫秒后,如果请求仍然没有得到结果,就会自动终止。该属性默认等于0,表示没有时间限制

  如果请求超时,将触发ontimeout事件

copy code
var xhr = new XMLHttpRequest();
btn.onclick = function(){
    xhr.abort();
};
xhr.ontimeout = function(){
    console.log('The request timed out.');
}
xhr.timeout = 100;
xhr.onabort = function(){
    console.log("The transfer has been canceled by the user.");
}
xhr.onerror = function(){
    console.log("An error occurred while transferring the file.");    
}
xhr.onloadend = function(){
    console.log("Request ended");    
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324776389&siteId=291194637