search
HomeWeb Front-endJS TutorialIn-depth understanding of ajax's XHR objects

This time I will bring you an in-depth understanding of the XHR object of ajax. What are the things to note when using the XHR object of ajax? The following is a practical case, let’s take a look.

The previous words Ajax is the abbreviation of asynchronous

javascript

and XML. The Chinese translation is asynchronous javascript and XML. This technology can request additional data from the server without unloading the page, which will bring a better user experience. Although XML is in the name, ajax communication has nothing to do with the data format. The following will introduce the content of ajax in detail

Creation The core of ajax technology is the XMLHttpRequest object (XHR for short), which was first introduced by Microsoft A feature that other browser providers later provided identical implementations of. XHR provides a fluent interface for sending requests to the server and parsing server responses. It can obtain more information from the server asynchronously, which means that after the user clicks, he can obtain new data without refreshing the page

 IE5 It was the first browser to introduce XHR objects. In IE5, the XHR object is implemented through an ActiveX object in the MSXML library, while IE7+ and other standard browsers support native XHR objects

Creating an XHR object is also called instantiating an XHR object. Because XMLHTTPRequest() is a

constructor

. The following is a compatible way of writing an XHR object

var xhr;
if(window.XMLHttpRequest){
  xhr = new XMLHttpRequest();
}else{
  xhr = new ActiveXObject('Microsoft.XMLHTTP');
}

Send a request

open()

When using an XHR object, the first method to be called is open(), which accepts 3 parameters: the type of request to be sent ("get", "post", etc.), the URL of the request and whether to send the request asynchronously The Boolean value

xhr.open("get","example.php", false);

[Note] The URL is relative to the current page where the code is executed, and requests can only be sent to URLs in the same domain using the same port and protocol. If the URL is any different from the page that initiated the request, a security error will occur.

#send()

The send() method receives a parameter, which is to be sent as the request body. The data. After calling the send() method, the request is dispatched to the server

xhr.open("get", "example.txt", false);
xhr.send(null);

Receive response After receiving the response, the response data will automatically Fill in the properties of the XHR object, mainly including the following 4 properties

responseText: The text returned as the response body

responseXML: If the content type of the response is 'text/xml' or 'application/ xml', this attribute will store the XML DOM document of the response data

status: HTTP status of the response

statusText: Description of the HTTP status

After receiving the response , the first step is to check the status attribute to determine that the response has been returned successfully. Generally speaking,

HTTP status code

of 200 can be used as a sign of success. At this point, the content of the responseText attribute is ready, and responseXML can also be accessed if the content type is correct. In addition, a status code of 304 means that the requested resource has not been modified, and the cached version in the browser can be used directly; of course, it also means that the response is valid Regardless of the content type, the content of the response body will be saved to the responseText attribute, and for non-XML data, the value of the responseXML attribute will be null

if((xhr.status >=200 && xhr.status <p style="text-align: left;"></p><p style="text-align: left;">asynchronous<span style="color: #ff0000"><strong></strong></span> If necessary What is received is an asynchronous response, which requires detecting the readyState attribute of the XHR object, which represents the current active stage of the request/response process. Possible values ​​for this attribute are as follows: </p><p style="text-align: left;">0 (UNSENT): Uninitialized. The open() method has not been called </p><p style="text-align: left;">1(OPENED): Start. The open() method has been called, but the send() method has not been called </p><p style="text-align: left;">2(HEADERS_RECEIVED): Send. The send() method has been called and the header information </p><p style="text-align: left;">3(LOADING): received. Partial response body information has been received </p><p style="text-align: left;">4 (DONE): Complete. All response data has been received and can be used on the </p> client<p style="text-align: left;"><a href="http://www.php.cn/code/10550.html" target="_blank"><p style="text-align: left;">  只要readyState属性值由一个值变成另一个值,都会触发一次readystatechange事件。可以利用这个事件来检测每次状态变化后readyState的值。通常,我们对readyState值为4的阶段感兴趣,因为这时所有数据都已就绪</p>
<p style="text-align: left;">  [注意]必须在调用open()之前指定onreadystatechange <a href="http://www.php.cn/code/5690.html" target="_blank">事件处理</a>程序才能确保跨浏览器兼容性,否则将无法接收readyState属性为0和1的情况</p>
<pre class="brush:php;toolbar:false">xhr.onreadystatechange = function(){
  if(xhr.readyState === 4){
    if(xhr.status == 200){
      alert(xhr.responseText);
    }
  }
}

实例

  下面以一个小实例来演示ajax中xhr对象的应用

<button>获取信息</button>
<p></p>
<script>
btn.onclick = function(){
  //创建xhr对象
  var xhr;
  if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
  }else{
    xhr = new ActiveXObject(&#39;Microsoft.XMLHTTP&#39;);
  }
  //异步接受响应
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
      if(xhr.status == 200){
        //实际操作
        result.innerHTML += xhr.responseText;
      }
    }
  }
  //发送请求
  xhr.open(&#39;get&#39;,&#39;message.xml&#39;,true);
  xhr.send();
}
</script>

//message.xml

<p>hello world</p>

最后

  通过实例的演示发现,ajax前端本身的内容并不难。但是,由于ajax涉及到一些后端及网络的知识,使得学起来不是很容易。以后的博文将逐步深入地介绍ajax的重点内容

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

AJAX的队列请求如何实现(附代码)

pushState+Ajax实现无刷新的页面切换

The above is the detailed content of In-depth understanding of ajax's XHR objects. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function