Ajax Basics Tutorials (i) _ajax related

Source: Internet
Author: User
Tags php language

What is Ajax?

Before we study 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 you rarely hear about Web 1.0, it actually refers to a traditional web with a completely different request and response model." For example, click a button on the hdu.edu.cn website. A request is sent to the server, and then the response is returned to the browser. This request is not just a new content and a list of items, but another complete HTML page. So when a Web browser is redrawn with a new HTML page, you may see flicker or jitter. In fact, you can see the requests and responses clearly from each new page you see.

Ajax is also a prerequisite for the front-end skills, learning any language, you need a lot of theoretical practice to really learn, before learning Ajax many times, because the lack of a lot of practice, always forget. So not practice is the mother of failure ... Of course the rationale is also important, and today I'll talk about my basic knowledge of Ajax.

definition: Full Name: Asynchronous JavaScript and XML, which uses asynchronous JavaScript to manipulate XML, is used to transmit data, which is actually sending data.

application: Let's think about the HTML code we write, when we change the contents of the inside and want to see the effect, is not first save, and then go to the browser to refresh the page, and Ajax is to do when the page content changes can not refresh the page, you can tell us the change. For example, we register when information filling error, is not refreshing the page can see the information directly, for example, when we play QQ, what news will remind you, there is no refresh page, the slightest influence you do other things, this is what Ajax do.

Here we first do not parse the specific principle, first look at a general implementation process.

Of course, first of all, you have to know is to put the code running under the server, open the time can not use the local address, to use localhost/. This form is accessed under the service. If this does not understand, you can first by yourself under Baidu.

Chestnut demand: A new text 1.txt, random input what content, new HTML page, click on the page button to get the content of 1.txt inside

var obtn = document.getElementById (' btn ');
Obtn.onclick = function () {
var xhr = new XMLHttpRequest ();//Create Ajax Object
xhr.open (' Get ', ' 1.txt ', true);//Set Request information 
xhr.send ()//Submit Request
//wait for server to return content
Xhr.onreadystatechange = function () {
if (xhr.readystate = 4) {
alert (Xhr.responsetext); Popup Content
}}} 

When you click on the button, you will notice that the contents of the 1.txt are popped up.

Let's make a concrete analysis of this step.

var xhr = new XMLHttpRequest (); Creating Ajax Objects

We want to use Ajax to get the data, first of all, to create an Ajax object, and you want to get the system time to create a time object is a truth. The name of the object is XMLHttpRequest (), so that we can interact with the method properties under the object after it has been created.

What needs to be explained is that this object actually has the compatibility problem, the IE6 below does not have this object, therefore is obtains the data, IE6 the following use actually is a plug-in way:

ActiveXObject (' microsoft.xmlhttp ') 
//activexobject:ie6 under the general name of Plug-ins, contains a lot of Plug-ins
//microsoft.xmlhttp: a specific plug-in names

So we need to do a compatibility deal with the above:

var xhr = null;
if (window. XMLHttpRequest) {//Add window is because if you directly judge IE does not exist things will be an error, add window, is to determine whether a property exists, so there will be no error (of course, we all know that everything is under the Window object, So the judgment is valid)
XHR = new XMLHttpRequest ();
} else{
xhr = new ActiveXObject (' microsoft.xmlhttp ');
}

Then look.

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

Open method

Three the meaning of a parameter

1, the way of submission Form-method (Get/post)

2. Submit Address Form-action

3, whether asynchronous, is for (true)

First, the way to submit: Get/post The difference between the two.

Here we do not use the Ajax way, first directly through the traditional form submission data to analyze.

The traditional form submission is to set some of the submitted parameters in the form, the user's information input submitted, will jump to the specified background page.

Parameters for the form:

Action: Where to submit the default is the current page

Method: Submit by default is get

ENCTYPE: Submitted data format, default is application/x-www-form-urlencoded

Let's look at the chestnuts requested by the Get method and see how the front and rear ends interact.

Chestnut requirements: Create HTML page, PHP page, fill in data, click Submit, and then output the content we entered.

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 (If you do not know the PHP language, probably look at the following comments simple know what to do)

<?php
Header (' content-type:text/html;charset= ' utf-8 ');//Set encoding format, and document type
error_reporting (0);
$username = $_get[' username '];//gets the data
$age = $_get[' age ' of the Get request method;
echo "Your name: {$username}, Age: {$age}"; Output content

When you click on the button, the page jumps to the 1.get.php page and outputs the content. And looking at the address bar above, we will find that the information we entered is placed on the address bar.

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

1 Input user information, click Submit, jump to the designated background of the page

The 2 Get method concatenates the data names and corresponding values entered by the user in such a format (Username=value&age=value), placing the question mark on the address bar of the specified background page (?). Behind

3 backstage code through the $_get method in the PHP language, obtains the user information in the Address bar, $_get[' username ']; $_get[' age ']; then assign to the variable and output the information.

From this, we can know the get way:

1 concatenate the data name with the corresponding value (Username=value&age=value), and then put the data to the URL of the specified page? Behind.

2 we can actually change the user information manually in the address bar of the background page, and the corresponding output will change. Because the background code is the information obtained from the address bar.

So also because of this, this transmission is not safe,

There are some other features of Get mode:

3 because the URL has a length limit reason GET request way has the data quantity limit, each browser is different, so do not pass too long data in this way. Otherwise it will be intercepted, resulting in incomplete delivery of data.

4 can only pass string type

Here's a look at the post method, which is also the requirement

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

<?php
Header (' content-type:text/html;charset= "Utf-8");
error_reporting (0);
$username = $_post[' username '];//different request method methods, the $_post method is specifically used to obtain the data $age of the POST mode request = $_post[' age ']; echo "Your name: {$username}, Age: {$age}";


1. Input page, as before the interception, output information page, we can see that the address bar has no user information, but the page or output the user information. So where do you see the process of transmission?

In fact, in the process of passing data, the browser will also send a request header to the server (background) contains some request information (GET request also has header information), we open the Developer tool, find the network can see our request, click on the specific content, look at the second diagram above, you can see some request information, Have the requested encoding format, as well as the request address, you can personally understand the details.

We look at the third map, you can see the requested data, the above is actually the browser has been entered in a certain format of information, the following source code is the actual transmission of information, you can see the format of the concatenation and get request is the same, but the user name encrypted, more secure.

From this we can know

POST request

1 The serial format of the data is the same as the GET request

2 transmission through the browser via the request header information:

There's another difference.

3 Transmission data volume post theoretically infinite

4 can pass multiple data types (text type, binary)

There must be back-end get data format not only $_get, $_post also has a 3 $_request can get any data submitted.

What we need to be aware of is that the data transfer mode and the method of obtaining the information must be consistent to successfully acquire

About the first parameter submission for the Open method here, the second address is easy to understand, and here's the third argument about Asynchrony and synchronization.

Sync: is a blocking mode, such as code var a =1 alert (a); This is a synchronization, and you must execute the first var a = 1 before you pop a value.

Disadvantages: Generally when the code behind you need to use the front of the things suitable for synchronization, but with very little, because the following code must wait for the front, experience is not good.

Asynchronous: is a non-blocking mode, the most obvious example is the timer, when we write a 30s after the execution of the timer, in the 30S in fact, the following code can be executed, rather than after the 30s code to execute, this is an asynchronous.

Disadvantage: When the code behind you need to use the previous things, if asynchronous, then the following code will not be loaded in front of the out, there may be problems. Luckily, we can solve it.

Solution: When the code behind you needs to use the previous things, you can use conditional judgment to determine the execution of the code, if the conditions are reached.

and take the top of the chestnut.

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 Request
//wait for server to return content here will be specific, probably listening to the state of the server, first simple to understand can be
Xhr.onreadystatechange = function () { 
if (xhr.readystate = 4) {//if docking received data corresponding to, and parsing completion
alert (xhr.responsetext);/popup content 
} 
}< c16/>}

It takes time to submit a request in the code above, so you have to wait until a certain time to commit successfully before we can get to the content correctly, so that's the code that follows correctly, depends on the xhr.send, but if you use synchronization, The code behind us that doesn't rely on the preceding code is not going to work, so we choose to use Asynchrony, and for those code that relies on the previous code, we're going to be able to judge

if (xhr.readystate = 4) is to determine if the data response to, received, and then pop-up content. ( If we do not judge, according to the principle of asynchronous, will immediately bounce out, get the data need time, because the actual has not yet acquired data, so will be pop-up empty, afraid of misunderstanding, so here I emphasize ).

The above is a small set to introduce the AJAX basic detailed tutorial (a) of the relevant knowledge, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.