Home  >  Article  >  Web Front-end  >  In-depth analysis of ajax progress events (with examples)

In-depth analysis of ajax progress events (with examples)

不言
不言forward
2019-03-27 09:25:442322browse

The content of this article is about in-depth analysis of ajax progress events (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Generally, use the readystatechange event to detect the completion of the HTTP request. The XHR2 specification draft 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 attribute. This draft defines events related to client-server communication. These events were actually only targeted at XHR operations at first, but are now also used by other APIs (such as File API). This article will introduce progress events in detail

Basics

There are the following 6 progress events

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

progress: Continuously triggered while receiving the response

error: Triggered when an error occurs in the request

abort: Triggered when the connection is terminated due to calling the abort() method

load: Triggered when complete response data is received

loadend: Triggered after communication is completed or error, abort or load event is triggered

timeout: Triggered when timeout occurs

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

Each request starts by triggering the loadstart event. Next, progress is usually triggered every 50 milliseconds or so. event, then trigger one of the load, error, abort or timeout events, and finally end with triggering the loadend event

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

load
The load event will be triggered after the response is received, so there is no need to check the readyState attribute. But a completed request is not necessarily a successful request. For example, the handler of 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

<button id="btn">获取信息</button>
<p id="result"></p>
<script>
btn.onclick = function(){
//创建xhr对象
var xhr;
if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
}else{
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
//进度事件
xhr.onload = function(){
    if(xhr.status == 200){
        result.innerHTML += xhr.responseText;
    }
}
//发送请求
xhr.open('get','message.xml',true);
xhr.send();
}
</script>

progress

The progress event is triggered periodically while the browser receives new data. The onprogress event handler will receive an event object whose target attribute is the XHR object, but contains three additional attributes: 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 determined based on the Content-Length response header. With this information, it is possible to create a progress indicator for the user

<button id="btn">获取信息</button>
<p id="result"></p>
<p id="music"></p>
<script>
btn.onclick = function(){
//创建xhr对象
var xhr;
if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
}else{
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
//进度事件
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);
        }
    }
};
//发送请求
xhr.open('get','myocean.mp3',true);
xhr.responseType = 'blob';
xhr.send();
}
</script>

Upload Progress
In addition to the useful events defined for monitoring the loading of HTTP responses, XHR2 also provides Events uploaded by HTTP requests. In browsers that implement these features, the XMLHttpRequest object will have an upload attribute. The upload attribute 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 attribute, upload can only trigger new event types)

Can only Use the upload event handler like a normal progress event handler. For the XMLHttpRequest object, set XHR.onprogress to monitor the download progress of the response, and set XHR.upload.onprogress to monitor the upload progress of the request

<input type="file" name="file1" id="file1" style="display:none">
<button id="btn">上传文件</button>
<p id="pro"></p>
<p id="result"></p>
<script>
btn.onclick = function(){
file1.click();
pro.innerHTML = result.innerHTML = '';
}
file1.onchange = function(){
//创建xhr对象
var xhr;
if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
}else{
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var data = file1.files[0];
//上传事件
xhr.upload.onprogress = function(e){
    e = e || event;
    if (e.lengthComputable){
        pro.innerHTML = "上传进度为:" + e.loaded + " of " + e.total + " bytes" + ';百分比为:' + e.loaded/e.total;
    }
}
xhr.onload = function(e){
    var data = xhr.responseText;
    e = e || event;
    if(xhr.status == 200){
        result.innerHTML =  data;
    }
};
//发送请求
xhr.open('post','pp.php',true);
xhr.setRequestHeader("content-type",data.type);
xhr.send(data);
}
</script>
<?php
error_reporting(E_ALL & ~E_NOTICE);
touch($file);
if(preg_match(&#39;/image/&#39;,apache_request_headers()[&#39;content-type&#39;])){
$file = &#39;photo/test.jpg&#39;; 
binary_to_file($file);
echo &#39;文件上传成功!&#39;;
}else{
echo &#39;文件格式不正确,请选择图片文件&#39;;
}
function binary_to_file($file){
$content = $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;];  // 需要php.ini设置
if(empty($content)){
    $content = file_get_contents(&#39;php://input&#39;); //不需要php.ini设置,内存压力小
}
$ret = file_put_contents($file, $content, true);
return $ret;
};
?>

Other events

The HTTP request could not be completed There are 3 situations, corresponding to 3 types of events. If the request times out, the timeout event will be triggered. If the request is aborted, the abort event will be triggered. Finally, network errors like too many redirects can prevent the request from completing, but an error event is triggered when these situations occur. You can cancel an ongoing HTTP request by calling the abort() method of the XMLHttpRequest object. Calling the abort() method triggers the abort event on this object

The main reasons for calling abort() are when a canceled or timed-out request takes too long to complete or when the response becomes irrelevant. Suppose you use XMLHttpRequest to request autocomplete recommendations for a text input field. If the user enters new characters before the server's suggestions are reached, then waiting for the request is no longer useful and should be aborted

The timeout attribute of the XHR object is equal to an integer, indicating how many milliseconds later, if the request still does not get the result, will automatically terminate. This attribute defaults to 0, which means there is no time limit.

If the request times out, the ontimeout event will be triggered

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("请求结束");    
}

This article is all over here. For more other exciting content, you can follow PHP Chinese website’s

JavaScript video tutorial

column!

The above is the detailed content of In-depth analysis of ajax progress events (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete