This time I will bring you a detailed analysis of the skills of using Ajax in JS, and a detailed analysis of the precautions for using Ajax in JS. The following is a practical case, let's take a look.
Ajax is not a new programming language, but a new way of using existing standards. AJAX can exchange data with the server without reloading the entire page. This asynchronous interaction method allows users to obtain new data without refreshing the page after clicking.
XMLHttpRequest object
The core of Ajax is the XMLHttpRequest object (XHR). XHR provides an interface for sending requests to the server and parsing server responses. Ability to get new data from the server asynchronously.
Create objects in the browser(Only supports IE7 and higher versions):
var xhr = new XMLHttpRequest();
Usage of XHR
The first thing to introduce is the open() method. It receives 3 parameters: • The type of request to send (POST, GET, etc.) • The URL of the request • A Boolean value indicating whether to send the request asynchronouslyExample of calling open():
xhr.open("get", "index.jsp", false);GET for index.jsp ask. The URL is relative to the current page where the code is executing; calling the open() method does not actually send the request, it just initiates a request to be sent.
Call send() to send a request:
xhr.send(null);send() receives a parameter, which is to be used as the request body sent data. If you do not need to send data through the request body, you must pass in null. The corresponding data will be filled in the relevant properties of the XHR object: •responseText: the text returned as the response body•responseXML: the content type of the response is "text /xml” or “application/xml”•status: HTTP status of the response•statusText: Description of the HTTP statusAfter receiving the response, first check the status attribute , confirm that the response has been returned, generally 200 as a sign of success. Status code 304 indicates that the resource has not been modified and the cached version in the browser can be used directly. In order to receive an appropriate response, both status codes should be detected as follows:xhr.open("get", "index.jsp", false); xhr.send(null); if ((xhr.status >= 200 && xhr.status By detecting the readyState attribute, the current active stage of the request/response process can be determined. <p style="text-align: left;"></p>•0: Not initialized. The open() method was not called<p style="text-align: left;"></p>•1: Start. The open() method has been called, but the send() method has not been called<p style="text-align: left;"></p>•2: Send. The send() method has been called and no response has been received <p style="text-align: left;"></p>•3: Received. Partial data has been received <p style="text-align: left;"></p>•4: Complete. All data has been received and can be used on the <p style="text-align: left;"> client. When the value of the <a href="http://www.php.cn/code/10550.html" target="_blank"></a></p>readyState attribute changes, a readystatechange event will be triggered. Specifying the onreadystatechange<p style="text-align: left;"> event handler<a href="http://www.php.cn/code/5688.html" target="_blank"> program before calling open() can ensure browser compatibility. </a></p><pre class="brush:php;toolbar:false">var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if ((xhr.status >= 200 && xhr.status Before receiving the response, the asynchronous request can be canceled: <p style="text-align: left;"></p>xhr.abort();<p style="text-align: left;"></p>HTTP header information<p style="text-align: left;"></p>The XHR object provides operations Methods for request headers and response header information. <p style="text-align: left;"></p>By default, when sending an XHR request, the following header information will also be sent. <p style="text-align: left;"></p>•Accept: The content type that the browser can handle<p style="text-align: left;"></p>•Accept-Charset:The character set that the browser can display<p style="text-align: left;"></p>•Accept-Encoding:The type that the browser can handle Compression encoding<p style="text-align: left;"></p>•Accept-Language: The language currently set by the browser<p style="text-align: left;"></p>•Connection: The type of connection between the browser and the server<p style="text-align: left;"></p>•Cookie: The language set by the current page Any Cookie<p style="text-align: left;"></p>•Host: The domain where the requested page is located<p style="text-align: left;"></p>•Referer: The URL of the requested page<p style="text-align: left;"></p>•User-Aent: The user agent character of the browser string<p style="text-align: left;"></p><p style="text-align: left;">使用setRequestHeader()可以设置自定义的请求头部信息。必须在调用open()方法之后,且在调用send()之前,调用</p><p style="text-align: left;">setRequestHeader():</p><pre class="brush:php;toolbar:false">xhr.open("get", "index.jsp", true); xhr.setRequestHeader("MyHeader", "MyValue"); xhr.send(null);
调用getResponseHeader()并传入字段名称,可以取得相应的响应头部信息。getAllResponseHeader()取得包含所有头部信息的长字符串。
var myHeader = xhr.getResponseHeader("MyHeader"); var allHeaders = xhr.getAllResponseHeader();
GET请求
GET用于向服务器查询某些信息。可以将查询字符串参数追加到URL的末尾,查询字符串中的每个参数的名称和值都必须使用encodeURIComponent()编码:
xhr.open("get", "login.jsp?name1=value1&name2=value2", false); addURLParam()接收三个参数:要添加参数的URL、参数的名称和参数的值。 var url = "login.jsp"; // 添加参数 url = addURLParam(url, "username", "xxyh"); url = addURLParam(url, "password", "xxyh123"); // 初始化请求 xhr.open("get", url, false);
POST请求
POST请求用于向服务器发送应该被保存的数据。POST请求的主体可以包含非常多的数据,而且格式不限。
初始化请求:
xhr.open("post", "login.jsp", true); 首先将Content-Type头部信息设置为application/x-www-form-urlencoded,然后建立一个字符串格式。如果需要将页面中的表单数据进行序列化,然后再通过XHR发送到服务器,可以使用serialize()函数来创建这个字符串: xhr.open("get", "login.jsp", false); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var form = document.getElementById("user-info"); xhr.send(serialize(form));
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed analysis of Ajax usage skills in JS. 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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

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