Home  >  Article  >  Web Front-end  >  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)

寻∝梦
寻∝梦Original
2018-09-10 11:45:091996browse

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);

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)
                }
            }
        })
    })
});

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:
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