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

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

Mar 27, 2019 am 09:25 AM
javascript

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>
Copy after login

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>
Copy after login

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 = '';
}
Copy after login
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>
Copy after login
<?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;
};
?>
Copy after login

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

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles