Home > Web Front-end > JS Tutorial > body text

How to use ajax correctly? Details of how to use ajax when you first get to know it

寻∝梦
Release: 2018-09-10 12:03:40
Original
1405 people have browsed it

This article mainly introduces the definition of ajax. For some people who have just met ajax, they still don’t understand it, so this article teaches you how to correctly understand ajax and the correct Learn ajax. Let’s read this article together now

I’m learning ASP.NET Ajax these days, and I’m a little confused, so I decided to learn Ajax first, and then transition to ASP.NET Ajax. This article will introduce Everyone is getting to know Ajax for the first time, looking at Ajax from a macro perspective, and then learning from the details. The outline of the article is as follows.

  • ##Ajax definition

  • Ajax composition

  • #XMLHttpRequest

  • ##Common Ajax usage

  • ##Ajax client life cycle

  • Implementation principle

  • A simple example

    ##Ajax definition


Ajax is the abbreviation of Asynchronous JavaScript and XML. It is not a new programming language, but a new method of using existing standards. The full name seems to only include JavaScript and XML. In fact, Ajax does not only include JavaScript and XML. Ajax is composed of JavaScript, XML, CSS, DOM and XMLHttpRequest.

Ajax composition

##Except Json and XMLHttpRequest, everything else used to be I have studied it before, so I will briefly introduce it.

1. HTML/XHTML: Used to describe the initial style of the Ajax page, that is, the page that is loaded and displayed for the first time. 2. DOM: Document Object Model (Document Object Model), used to represent XML data structure. 3. CSS: Cascading Style Sheet (cascading style sheet) expression, used to represent the style of elements in HTML files. 4. XML and JSON: XML is a standard data style, which can be well interpreted by both the server and the client.

JSON: JavaScript Object Notation, because of the format of JSON and the syntax of defining objects in JavaScript Consistently, for the same data, JSON is shorter than XML, reducing network traffic.

5. Server-side processing of browser requests: The developer can choose the method he is familiar with for server-side design and implementation. 6. XMLHttpRequest object: It allows developers to make HTTP requests to the server asynchronously in javaScript and get a response.
7. JavaScript: The above elements can be linked together through JavaScript, such as viewing and modifying DOM, CSS, etc. through JavaScript.





XMLHttpRequest object

## The XMLHttpRequest object is the technical foundation of AJAX and Web 2.0 applications , AJAX uses XMLHttpRequest to send and receive HTTP request and response information. An HTTP request sent via an XMLHttpRequest object does not require the page to have or post back a

element. The "A" in AJAX stands for "asynchronous", which means that the send() method of the XMLHttpRequest object can return immediately, allowing other HTML/JavaScript on the Web page to continue its browser-side processing while the server handles the HTTP request and sends it response. By default, the request is made asynchronously. You can also choose to send a synchronous request, which will suspend the processing of other Web pages until the page receives a response from the server. Use the XMLHttpRequest object to send the request Before processing the response, you must first create an XMLHttpRequest object using JavaScript.

(If you want to see more, go to the PHP Chinese website

AJAX Development Manual column to learn) XMLHttpRequest Attribute

##responseTextThe server's response, expressed as a string responseXML The server's response, expressed as XML. This object can be parsed into a DOM objectstatusThe HTTP status code of the server (200 corresponds to OK, 404 Corresponding to Not Found (not found), etc.)statusTextThe corresponding text of the HTTP status code (OK Or Not Found (not found), etc.)

Properties

Description

onreadystatechange

This event handler will be triggered every time the state changes, usually calling a JavaScript function

##readyState

The status of the request. There are 5 possible values: 0 = Not initialized, 1 = Loading, 2 = Loaded, 3 = Interactive, 4 = Complete

XMLHttpRequest method

MethodDescription##abort()##getAllResponseHeaders()getResponseHeader("header")open("method", "url")send(content)setRequestHeader("header", "value")

Stop the current request

Return all response headers of the HTTP request as key/value pairs

Returns the string value of the specified header

Establish a call to the server. The method parameter can be GET, POST or PUT. The url parameter can be a relative URL or an absolute URL. This method also includes 3 optional parameters

Send a request to the server

Sets the specified header to the provided value. open() must be called before setting any header

Use of Ajax

Why use Ajax? Because it can achieve asynchronous communication, partially refresh the page, and reduce the amount of data transmission, the most important point is to give users a better experience.

Ajax is very common in the current web, such as Google’s map, which will be reloaded every time you drag it area, but the page is not refreshed; Baidu’s search box, matching content appears after input; The content on Weibo is updated, and the page is not reloaded...

Ajax client life cycle

##Divides this cycle into six easily distinguishable processes. As follows:

(1) The user makes a browsing request for a certain URL. (2) The server sends the HTML page content to the browser.
(3) The browser creates DOM in memory based on the received HTML content.
(4) The user triggers an asynchronous request to the server. This will not affect the existing DOM, that is, user operations will not be interrupted.
(5) The browser sends the XML format data to the JavaScript function in the original page for processing.
(6) The browser parses the results, then updates the DOM in memory, and parts of the web page are updated, displaying the page very smoothly.

Implementation Principle

Ajax loading is the same as traditional web applications: first, enter the URL address or click the link to trigger An HTTP request is made to the browser; then the server processes the request, generates appropriate HTML, CSS and JavaScript, and sends them to the client; the client browser displays this piece of HTML; the responses to subsequent user operations begin to be different: these of the user The operation will not trigger another HTTP request from the browser, but will trigger the execution of a piece of JavaScript code on the client side.

No matter how vivid the description is, it is not as good as a picture:

How to use ajax correctly? Details of how to use ajax when you first get to know it

A simple example: Get the book title in book.xml without reloading the page.

HTML code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>book</title>
<script type="text/javascript">
    function loadXMLDoc() {
        var xmlhttp;
        var txt, x, i;
        if (window.XMLHttpRequest) {
        // 当今主流浏览器
            xmlhttp = new XMLHttpRequest();
        }
        else {
        // IE5、IE6
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //状态
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                xmlDoc = xmlhttp.responseXML;
                txt = "";
                //获取全部书名
                x = xmlDoc.getElementsByTagName("书名");
                for (i = 0; i < x.length; i++) {
                    txt = txt + x[i].childNodes[0].nodeValue + "<br />";
                }
                //把书名写到myp中
                document.getElementById("myp").innerHTML = txt;
            }
        }
        //使用get,异步项为true
        xmlhttp.open("GET", "book.xml", true);
        xmlhttp.send();
    }
</script>
</head>

<body>

<h2>我的藏书:</h2>
<br/>
<p id="myp"></p>
<br/>
<br/>
<button type="button" onclick="loadXMLDoc()">获取我的藏书</button>
 </body>
</html>
Copy after login

book.xml

##

<书籍>
  <书  类别="网络">
    <书名 lang="en">WEB开发</书名>
    <作者>M</作者>
    <年份>2008</年份>
    <价格>35</价格>
  </书>
  <书 类别="计算机">
    <书名 lang="en">存储体</书名>
    <作者>C</作者>
    <年份>2012</年份>
    <价格>30</价格>
  </书>
</书籍>
Copy after login

Running results: The results displayed without refreshing are as follows

How to use ajax correctly? Details of how to use ajax when you first get to know itThis article ends here (if you want to see more, go to the PHP Chinese website

AJAX User Manual

column to learn). If you have any questions, you can leave a message below.

The above is the detailed content of How to use ajax correctly? Details of how to use ajax when you first get to know it. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template