Ajax Basics Tutorials (ii) _ajax related

Source: Internet
Author: User
Tags commit browser cache

In the previous article to introduce the AJAX basic detailed tutorial (i), about Ajax in the open method of the third parameter asynchronous and synchronization problem, today, to continue to chatter, first followed by the code

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 ()//Commit request
/wait for server to return content 
Xhr.onreadystatechange = function () { 
if (xhr.readystate = = 4) {//if content responds successfully and resolves completion
alert (xhr.responsetext);//popup Content 
} 
}

Here we go, xhr.send (); This is the real request data, the Open method just sets some request parameters.

Now, the request is submitted, and so the server responds, this time an Ajax attribute is coming up, that is responsetext, the AJAX request to return the content is placed in this, and regardless of what you request the content, here is the string type.

Of course, we mentioned above, want to use asynchronous request, here need conditional judgment to know whether the server to request the content of the response completed, this time another attribute is coming, readyState, he represents the different state of the AJAX request process, the parameters are as follows:

0 (initialization) has not yet called the Open () method
1 (load) called Send () method, sending request
2 (load complete) Send () method completed, received all response content
3 (parsing) is parsing the response content (because the received content is not what people can read, so need to parse)
4 (complete) The response content parsing is complete and can be invoked on the client

From the top we can get, in the state of 2 has responded to the content of the request, but the content of our people do not understand Satan, the machine just understand, so there are 3, help us parse this content, and then the completion of the analysis into 4, this time the content, we can use the front end.

The state is there, but how can we know what time is the state, this time we will use a monitoring state of the event onReadyStateChange event, when the state value changes when the trigger will trigger this event, so when the state is 4 when we pop-up content.

The code above basically has understood the principle, but of course not the most perfect, this time, although we monitor the state, response to the content, but the content is not necessarily right, such as possible content error, maybe we asked for a non-existent page, this time readystate can not be judged wrong, We need to know whether the content is normal, this time another attribute Status property is on the scene, it represents not the Ajax state, but the state of the server (Request resources), the HTTP status code. There are many status codes, of which the more famous is 200, the success status code, and 404 Not Found. The rest of the public consulted privately. Here you can see.

So our code has to be further improved.

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 ()//Commit request
/wait for server to return content 
Xhr.onreadystatechange = function () { 
if (xhr.readystate = = 4) {if 
(Xhr.status = 200) {//If the response is successful and the server content is correct
alert (xhr.responsetext);/popup content 
}else{alert (' wrong ' + xhr.status); Otherwise tell an error and eject the error reason
} 
}

This is the approximate process of Ajax. Of course there are some details of the problem to be noted, continue to look down.

Problems with passing data in the back end of work:

GET Request:

1 caching problem: Background changes because the URL has not changed so will go to cache extract content instead of backstage

Look at a chestnut: if we want to click on the button to pop the name and age, because get requests are concatenated through numeric values and then pass the data on the URL, so our open method can write directly:

 
 

Background code does not change

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

Click now will definitely pop up your name Mu Qing, age 21.

This time, the browser will have a cache, if the next visit to the same URL, will be taken from the cache.

For example I want to eject now, welcome you, your name Mu Qing, age 21,

 
 

Although the background code has changed, but get requests to visit the URL is still 1.get.php?username= mu Qing &age=21, so the background will go to the browser cache, the results of the pop-up or original. You can test it yourself.

So, this time we need to solve the caching problem. Since access to the Web site will be to find the cache, then we let the Web site has not been better. So we can add a variable that's been changed in the back, like system events, or a random number, as follows:

 
 

This will not have a caching problem. Some people will write this, will give it a name in the back of T, this time if there is a variable in the background called T, may be a problem, so it is not very recommended.

 
 

POST request

1 Last lesson we know that the traditional way to post requests in a form is in the request, so where does Ajax go?

Post data is sent inside the Send as a parameter.

2 and one point is that we last saw the third parameter in the form: enctype: The data format submitted, the default is application/x-www-form-urlencoded, but in Ajax, you do not write, there is no default value, So we need to specify the submitted data format in the request header, otherwise the browser doesn't know which format to parse.

So the post request needs to set the following two sentences

Xhr.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');

There is no caching problem, because submitting data to the server alone will not be cached and the data will be cached. This is the web's mechanism.

All of the above are request data, now look at the backend receive request, and then respond to our content.

First look at the back-end of the data processing: back-end data types are also many, we can not directly to the front end of the data, so the backend also need to do some processing, it has a method json_encode can be based on the data type, and then output different formats. Look at the chestnuts below.

<?php
Header (' content-type:text/html;charset= "Utf-8");
error_reporting (0);
$arr 1 = Array (' Le ', ' Mo '); Data for index type
$arr 2 = Array (' username ' => ' le ', ' age ' =>32);//2 Correspondence Data
echo json_encode ($arr 1);//["le", "Mo" ] Index type output array format

Although the content format of the backend output is array and JSON but I mentioned earlier that alert (xhr.responsetext);//This pop-up can be all string types, the actual data type is still a string, although the format looks JSON and array.

So we're going to convert these strings on the front end. This is the time to use two methods.

1 stringify (): Converting a JSON object into a string converted string is a strict JSON format

2 Parse (): Turn the string into an object, you can turn the back-end string into a JSON format, for JSON, you can only convert a strictly JSON-formatted string, the string's key comparison in double quotes like this {"username": "le", "Age": 32}

Let's take a look at the actual case:

Requirements: Click on the page button, the implementation page does not refresh, display the news list below to see the comments should be able to understand

<! DOCTYPE html>  

Okay, today's Ajax is going to chatter here, hope that we have a harvest, if there is wrong hope everyone corrected, see a lot of people to see the avatar come in, the Roentgen family really do not know what to say, or hope that we can more rational point of view of the lesbian, next time will talk about the encapsulation of Ajax, as well as some practical applications.

The above is a small set to introduce the AJAX basic detailed tutorial (ii) of all the narrative, 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.