Ajax BASICS (1) and ajax Basics

Source: Internet
Author: User

Ajax BASICS (1) and ajax Basics

What Is Ajax?

Before studying ajax, let's first discuss a question-what is Web 2.0. When you hear the word Web 2.0, you should first ask "What is Web 1.0 ?" Although few people mentioned Web 1.0, it actually refers to the traditional Web with completely different request and response models. For example, click a button on the hdu.edu.cn website. Then a request is sent to the server, and the response is returned to the browser. This request is not only a new content and project list, but also a complete HTML page. Therefore, when a Web browser redraws an HTML page with a new one, it may see flashes or jitters. In fact, the request and response are clearly displayed on each new page.

Ajax is also a required front-end skill. Learning any language requires a lot of practices based on theory to truly learn it. I have learned Ajax many times before, because there is a lack of practice, I will always forget it. So not practice is the mother of failure... Of course, the theoretical basis is also very important. Today I will talk about my basic understanding of Ajax.

Definition:Full name: Asynchronous JavaScript and XML (using JavaScript in Asynchronous form to operate XML) is used to transmit data for interaction.

Application:Let's think about the HTML code we have written. When we change the content and want to see the effect, do we save it first, and then refresh the page in the browser, ajax is to notify us of the changes without refreshing the new page when the page content changes. For example, if we enter incorrect information during registration, we can directly see the information prompts without refreshing the new page. For example, when we play QQ, we will remind you of any messages and will not refresh the page at all, this is what Ajax does.

Next, let's look at a general implementation process without parsing the specific principles.

First of all, you must know that the code is run under the server. When it is opened, you cannot use a local address or localhost /.. This form is accessed under the service. If you do not know about it, you can go to Baidu first.

Chestnut demand: Create a new text 1.txt, enter the internal content, create a new HTML page, click the button on the page to get the content in 1.txt

Var oBtn = document. getElementById ('btn '); oBtn. onclick = function () {var xhr = new XMLHttpRequest (); // create an Ajax object xhr.open('get', '1.txt ', true); // set the request information xhr. send (); // submit the request // wait for the server to return content xhr. onreadystatechange = function () {if (xhr. readyState = 4) {alert (xhr. responseText); // pop-up content }}}

When you click the button, you will find the content in 1.txt.

Let's take a look at this step.

Var xhr = new XMLHttpRequest (); // create an Ajax object

We need to use Ajax to obtain data. First, we need to create an Ajax object. It is the same principle that you want to obtain the system time and create a time object. The object name is XMLHttpRequest (). After the object is created, we can use the method attributes under the object for data interaction.

It should be noted that this object is actually compatible, and IE6 does not have this object, so data cannot be obtained. IE6 is actually a plug-in method:

ActiveXObject ('Microsoft. xmlhttp') // ActiveXObject: general name of the plug-in under IE6, including many plug-ins // Microsoft. XMLHTTP: The name of a specific plug-in

Therefore, we need to handle the above compatibility:

Var xhr = null; if (window. XMLHttpRequest) {// Add a window because an error is reported if you directly judge that something does not exist in IE. if you add a window, you can determine whether an attribute exists, in this way, no error will be reported (of course we all know that everything is under the window object, so this judgment is valid) xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ('Microsoft. XMLHTTP ');}

See

Xhr.open('get', '1.txt ', true); // Set Request Information

Open Method

Meanings of the three parameters

1. Submission method Form-method (get/post)

2. submit the Form-action address.

3. Whether it is asynchronous. Yes (true)

First, let's talk about the difference between the two submission methods: get/post.

Here, we do not need to use ajax to directly analyze data submitted through traditional forms.

Traditional form submission is to set some parameters for submission in the form. User Information Input and submission will jump to the specified background page.

Form parameters:

Action: Where is the current page submitted by default?

Method: The default submission method is Get.

Enctype: Submitted data format. The default value is application/x-www-form-urlencoded.

Let's take a look at a get request and understand how the frontend and backend interact.

Chestnut requirement: Create an HTML page, PHP page, fill in the data, click submit, and then output the input content.

HTML page:

<Form action = "1. get. php "> <input type =" text "name =" username "> <input type =" text "name =" age "> <input type =" submit "value =" button "/> </form>

1. get. php)

<? Phpheader ('content-type: text/html; charset = "UTF-8" '); // you can specify the encoding format and file type error_reporting (0 ); $ username = $ _ GET ['username']; // obtain data in the get Request Method $ age = $ _ GET ['age']; echo "Your Name: {$ username}, age: {$ age} "; // output content

Observe the experiment results. When you click the button, the page will jump to the 1. get. php page and output the content. And observe the above address bar, we will find that the information we entered is placed on the address bar.

In fact, the entire GET request process is like this.

1. Enter the user information and click Submit to go to the page of the specified background.

2. The GET method Concatenates the data name entered by the user and the corresponding value in this format (username = value & age = value, question mark (?) in the address bar of the specified background page (?) .

3. The background Code uses the $ _ GET method in PHP to obtain the user information in the address bar. $ _ GET ['username']; $ _ GET ['age']; then assign the variable to output the information.

Therefore, we can know the GET method:

1. concatenate the data name and the corresponding value (username = value & age = value), and then place the data to the url address of the specified page? .

2. In fact, we can manually Change User information in the address bar of the background page, and the corresponding output will also change. Because the background code is obtained from the address bar.

Therefore, this transmission method is not safe,

The GET method has some other features:

3. The Get request method has a data size limit because the url length limit. Each browser has a different size. Therefore, do not use this method to transmit too long data. Otherwise it will be intercepted, resulting in incomplete transmitted data.

4. Only string types can be passed.

Let's take a look at the POST method.

HTML page:

<Form action = "1. get. php "method =" post "> <input type =" text "name =" username "> <input type =" text "name =" age "> <input type =" submit "value =" button "/> </form>

1. get. php

<? Phpheader ('content-type: text/html; charset = "UTF-8" '); error_reporting (0); $ username = $ _ POST ['username']; // different request methods are different. The $ _ POST method is used to obtain the data of the POST request. $ age = $ _ POST ['age']; echo "Your Name: {$ username}, age: {$ age }";

1. The input page is not intercepted as before. The output page shows that there is no user information in the address bar, but the page still outputs user information. Where can we see the transfer process?

In fact, in the process of data transmission, the browser will also send a request header containing some request information to the server (background) (the GET request also has header information). We open the developer tool, find the network and you will see our request. Click in to view the specific content. The second figure above shows some request information, including the request encoding format and request address, you can learn about it in private.

Let's look at the third figure. We can see the request data. The above is actually the information that the browser has input in a certain format. The source code below is the actually transmitted information, we can see that the format of the series connection is the same as that of the GET request, but the user name is encrypted, which is more secure.

From this we can know that

Post request

1. The connection format of data is the same as that of Get requests.

2. transmit the request header information through the browser:

Another difference is that

3. Theoretically unlimited Post Data Transfer

4. Multiple Data Types (text and binary) can be transferred)

There must also be a backend Data Acquisition format that includes not only $ _ GET, $ _ POST, but also a 3 $ _ REQUEST that can obtain data in any submission method.

We need to note that the data transmission method and the data acquisition method must be consistent before the data can be obtained successfully.

The first parameter submission method of the Open method is described here. The second address is described briefly. The following describes the asynchronous and synchronous parameters of the third parameter.

Synchronization: it is a blocking mode, such as code var a = 1; alert (a); this is a synchronization, the first var a = 1, the value of a is displayed.

Disadvantage: It is generally suitable for synchronization when the code behind you needs to use the previous things, but it is rarely used, because the code behind you has to wait for the front, and the experience is poor.

Asynchronous: it is a non-blocking mode. The most obvious example is the timer. When we write a timer 30 s later, in fact, the code after 30 s can be executed, rather than the code after 30 s, which is asynchronous.

Disadvantage: If Asynchronous is used when the code behind you needs to use the previous items, the subsequent code will be loaded before it is ready, which may cause problems. Fortunately, we can solve this problem.

Solution: When the code behind you needs to use the previous items, you can use condition judgment to determine the code execution. If the conditions are met, the code can be executed.

Also take the following example.

Var oBtn = document. getElementById ('btn '); oBtn. onclick = function () {var xhr = null; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new activexobject('microsoft.xmlhttp'{{{xhr.open('get', '1.txt ', true); // Set Request Information xhr. send (); // submit the request // wait for the server to return the content. Here we will talk about it in detail, which is probably the status of the listener server. You can simply get to know xhr. onreadystatechange = function () {if (xhr. readyState = 4) {// If the received data is matched, alert (xhr. responseText); // pop-up content }}}

In the above Code, xhr. it takes time to send () A request. Therefore, you must wait for a certain period of time until the request is successfully submitted before the content can be correctly obtained. Therefore, this means that the subsequent code is correctly executed, it depends on the front, but if we use synchronization, the code that does not rely on the front Code cannot be executed, and the experience is not good, so we choose to use Asynchronous, the code that depends on the previous code is judged.

If (xhr. readyState = 4) is to judge that if the data is returned, it is received, and then the content is displayed. (If we do not judge, it will immediately pop up based on the asynchronous principle. It takes time to obtain the data. Because the data has not been actually obtained, it will pop up blank, for fear of misunderstanding, so here I want to emphasize ).

The above section describes the relevant knowledge of the basic Ajax tutorial (1). I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.