Home Web Front-end JS Tutorial What exactly is ajax? Introduction to the background and use of ajax (with example analysis)

What exactly is ajax? Introduction to the background and use of ajax (with example analysis)

Sep 10, 2018 am 11:45 AM
ajax front end

This article mainly introduces the details of ajax, the specific meaning of ajax, and the instructions for using ajax. Let’s read this article together now

First let’s take a look at what ajax is?

We often hear the name ajax, so what is ajax?

1: Background introduction

First of all, speak with me, eh, don’t pronounce it as Ajax~.

AJAX = Asynchronous JavaScript and XML.

AJAX is not a new programming language, but a new way of using existing standards.

The biggest advantage of AJAX is that it can exchange data with the server and update part of the web page content without reloading the entire page.

AJAX does not require any browser plug-ins, but requires the user to allow JavaScript to execute on the browser.

2. Knowledge analysis:

Ajax is to use JS to initiate a request and get the content returned by the server. The biggest difference between this and previous technology is that "the page is not refreshed", which improves the user experience, that's all.

So how do we send an ajax request?

1. Create an object XMLHttpRequest

var xhr = new XMLHttpRequest(); In order to support ie6 and earlier versions, var xhr=new ActiveXObject()

2. Monitor the status changes after the request is successful

3. Set the request parameters

4. Initiate the request

5.Operation DOM, realizing dynamic partial refresh

And what is a completeHTTP request?

What exactly is ajax? Introduction to the background and use of ajax (with example analysis)

A complete request consists of four parts

What exactly is ajax? Introduction to the background and use of ajax (with example analysis)

Next, we need to monitor the status change of successful request

onreadystatechange: used to monitor changes in readyState

readyState: indicates the status of the background of the current request

status: indicates the result of processing

where readyState: Indicates the status of the background of the current request

0: The request has not been initialized (open() has not been called yet)

1: The request has been established, but has not been sent (send( has not been called yet) ))

2: The request has been sent and is being processed

3: The request is being processed, usually some data in the response is available

4: The response has been Completed, you can obtain and use the server's response

Andstatus: indicates the processing result (status code)

1XX, indicating that the request is being processed

status == 200 means that the processing result is OK

Status code: 200 to 300 means that the server returns normally

304: If the web page The server should be configured to return this response since it has not changed since the requester's last request, thereby saving bandwidth and overhead

404: Object not found

503: Server timeout

Set request parameters

xhr object accepts three parameters
1: Indicates the request type
2: Indicates the requested URL
3: Indicates whether it is asynchronous

get/post/put/delete

The difference between Get and post methods:

get is to obtain data, and the parameters of get’s send method can be null or empty. There is a limit to sending information, usually 2000 characters, generally used for query (idempotent)
Post can send data, but when using the post method to send data, you need to use setRequestHeader() to add HTTP headers. At the same time, post The send() method needs to write the value of the data to be sent. It is generally used to modify resources on the server. It has no limit on the amount of information and is safer (if you want to see more, go to the PHP Chinese websiteAJAX Development ManualStudy in the column)

3 Frequently Asked Questions

Use post to submit questions that require forgetting content-type

4.Solution

xhr.open("post", "/carrots-admin-ajax/a/login",true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("name=" + name + "&pwd=" + code);
Copy after login

Content-type should be placed as a request header between open and send

5. Encoding practice

var xhr = new XMLHttpRequest();
function ip() {
    var name = $("#name").val();
    var code = $("#code").val();
// 指定通信过程中状态改变时的回调函数
    xhr.open("post", "/carrots-admin-ajax/a/login",true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("name=" + name + "&pwd=" + code);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                if (JSON.parse(xhr.responseText).code >= 0) {
                    window.location.href = "http://dev.admin.carrots.ptteng.com/";
                } else {
                    $(".alert").html("该用户不存在或密码不正确");
                }
            }
        }
    };
}
$(function () {
    $("#summit").click(function () {
        var name = $("#name").val();
        var code = $("#pwd").val();
        $.ajax({
            type: "POST",
            url: "/carrots-admin-ajax/a/login",
            data: {
                "name": name,
                "pwd": code
            },
            // beforeSend: function(xhr){xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");},
            datatype:"json",
            success: function (data) {
                console.log(data);
                if (JSON.parse(data).code==0) {
                    alert(JSON.parse(data).message);
                }
                else {
                    alert(JSON.parse(data).message)
                }
            }
        })
    })
});
Copy after login

6 Extended thinking

What are the advantages and disadvantages of Ajax?

Reference

jqury ajax method

Novice tutorial

More discussions

1. What is the request body?

The request body encodes the component value in a page form into a formatted string in the form of key-value pairs of param1=value1¶m2=value2, which carries the data of multiple request parameters. . Not only the message body can pass request parameters, but the request URL can also pass request parameters in a method similar to "/chapter15/user.html?param1=value1¶m2=value2".

2.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

What does application/x-www-form-urlencoded mean?

The enctype attribute of form is the encoding method. There are two commonly used ones: application/x-www-form-urlencoded and multipart/form-data. The default is application/x-www-form-urlencoded.

x-www-form-urlencoded

When the action is get, the browser uses the x-www-form-urlencoded encoding method to convert the form data into a word String (name1=value1&name2=value2...), then append this string to the end of the url, split it with ?, and load this new url.

3. How does jQuery set the accepted data types?

Use datatype: "json" and write the data type you want to accept

This article ends here (if you want to see more, go to the PHP Chinese websiteAJAX User Manual column), if you have any questions, you can leave a message below.

The above is the detailed content of What exactly is ajax? Introduction to the background and use of ajax (with example analysis). 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

See all articles