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>获取信息</button> <p></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>获取信息</button> <p></p> <p></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> <button>上传文件</button> <p></p> <p></p> <script> btn.onclick = function(){ file1.click(); pro.innerHTML = result.innerHTML = ''; }</script>
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); }
<?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 '文件上传成功!'; }else{ echo '文件格式不正确,请选择图片文件'; } function binary_to_file($file){ $content = $GLOBALS['HTTP_RAW_POST_DATA']; // 需要php.ini设置 if(empty($content)){ $content = file_get_contents('php://input'); //不需要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 tutorialThe 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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.