Ajax Learning Notes

Source: Internet
Author: User

In the early time, we have been exposed to Ajax, including the native Ajax request method, cross-domain Ajax request methods, HTTP related knowledge. This time to write Ajax is mainly a review of the knowledge before learning, because I found that before I was playing the memorized things gradually forgotten by me. I found this forgotten very scary, looking back on the knowledge I learned before, found that a lot of things are vague some images, but really want to think and can't remember, so I think there is a platform to learn from their own things recorded. This way, whether it's a share or a review, it's good for a developer.

First of all, the most basic, Ajax in fact, has been put forward, the specific time, for the people who are bent on learning technology, I can only say, I also forgot ... But time is not the key, the key is why to have Ajax, what is the use of Ajax. The advent of Ajax was the first to solve the difficult problem of the previous form, before the Ajax technology, the user to fill out a long form, then he spent half a day to fill out the form, and then clicked on the next submission. This time the data sent to the backstage, after a series of verification backstage, found that you do not fill in one of them, at this time you have to re-check the form you filled out, and then submitted after the completion of a half-day after the background verification. found that the phone number you filled out is incorrect. After a couple of times, users are not starting to curse, they have decisively closed your page. At this time, the advent of Ajax becomes very necessary, through the Ajax, we can achieve a user each input to complete a message, you can send an asynchronous verification, to determine whether the user fill in the information to meet the requirements. In this way, users can be very intuitive to see whether the data is standardized, whether or not to fill out the explanatory data.

After talking about the benefits of Ajax, say something about the actual content, since Ajax is so good, how do we use it, first, we're going to create an asynchronous object

var request=new xmlhttprequest ();

But here's the problem, that IE5 and IE6 don't support this object, so we can write a compatibility code

var request;
if (window. XMLHttpRequest) { request=new XMLHttpRequest ();//compatible with IE7 and above}else{request=new activvexobject (" Microsoft.xmlgttp ");//compatible with IE5,IE6}

In this way, we create a compatible Ajax object. After creating the Ajax object, we can send the data like a background. Send the request to use an open method and the Send method, first of all, the open method, the open method is used to define the way the request (get or post,get is generally used for information acquisition, using the URL to pass parameters, the information sent is limited, the maximum is not more than 2000 characters. Post is generally used to modify resources on the server, the amount of information sent is theoretically infinite), the path of the request and whether it is asynchronous, that is, he receives three parameters, such as:

Open (' GET ', ' index.php ', true);

The third parameter, by default, is true, which means that it is asynchronous, so it can be filled out. Then send, he takes a string parameter to write to the data to be transferred, generally speaking, if the request is get, the data is transmitted by the URL followed by the parameter, so if the method in open is get, the value here is generally empty, If the method is post, then the data can be filled in send. When using post to transfer data, be sure to add a request header to tell the server that this is a form submission. The code is as follows:

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

In this way, we can send data like the background, but how can we tell if the server is receiving the data, then we need to use an object to listen to the request.

 

request.onreadystatechange=function () {    if (request.readystate===4&&request. status===200) {        console.log (request.responsetext);    }}

There are several new methods, but all very simple, the first is onreadystatechange, this is what I said before the state of the Listener server object, then listen to how to see the server is what state it, This is the time to use the function inside the readystate and status two attributes. ReadyState altogether has five values, respectively:

0: Request initialization, open not yet called

1: Server connection established, open has been called

2: Request received, request header information received

3: The response body is received in request processing

4: The request is complete and the response is ready

Similarly, the status is valued a lot, but we are most concerned about the state of his request for success, that is, when status equals 200. When readystate equals 4 and status equals 200, it means that the request is complete, and then we can do something about the data in response. There are many ways to do this, such as

ResponseText: Getting response data in string form

Responsexml: Returning HTTP status codes as numbers and literals

Status and StatusText: Returns the HTTP status code as a number and text

Getallresponseheader (): Gets all the response headers

getResponseHeader (): The value of a field in a query response

In addition to the native methods, there are encapsulated Ajax requests in jquery, which I don't mention, and I'd like to look at jquery's documentation on Ajax.

In this way, a complete AJAX request is complete. Here, I would like to expand two points, one is the HTTP protocol, the other is a cross-domain problem, these two things in the reference to Ajax will always follow.

First of all, HTTP, what is HTTP, in short, HTTP is a computer network to communicate the rules. He's a stateless protocol, and may feel a bit blindfolded for the first time, but not so much because it's just an extension, and knowing that he can help us gain a deeper understanding of the interactions between the front and back ends, of course, if it doesn't make too much of a difference for the novice programmer, It is enough for the novice programmer to master the simple Ajax sending request and receiving the data. The HTTP request is simple in terms of the following seven steps:

1. Establishing a TCP link

2.web Browser sends request command to Web server

3.web Browser sends request header information

4.web Server Answer

5.web server sends answer header information

6.web server sends data to browser

7.web Server shutdown TCP link

What data does the HTTP request request? Or what is included in his request? HTTP is made up of four parts, namely

1. The method and action of the request, that is, whether your methods are get or post

2. The requested address, i.e. where the data is sent to

3. Request header, he contains some information about the client, including some authentication information

4. The request body, which contains the string information and form information submitted by the customer

After sending the request, the service side will also give us a certain response, the response is composed of three parts, namely:

1. A number and text status code to show that the request succeeded or failed

2. Response header: Similar to the request header, contains server information such as server type, date and time, content type and length

3. Response body: The body of the service-side response

There are many status codes for HTTP responses, but there are not five types:

1XX: Information class that identifies the Web server that received the request and is further processing

2XX: Successful, identify user requests are received, understood and processed correctly

3XX: Redirect, identity request not successful, customer must take further action

4XX: Client error, indicating that the client submitted a request with an error

5XX: Server error, indicating the server could not complete processing of the request

The HTTP protocol, and then the cross-domain problem, in the usual simple project, may not involve this, the problem, but if the project needs you to visit different domain data, there will be cross-domain issues, what is called cross-domain, before understanding the cross-domain, we have to understand the composition of the URL, Take http://www.abc.com:8080/script/jquery.js this site, HTTP//Is his protocol name, www is a subdomain, abc.com is the primary domain name, 8080 is the port number,/script/ Jquery.js is the requested resource address. Of course, we may have seen www.abc.abc.com domain name, here www.abc is a subdomain, abc.com is the primary domain name. After understanding the composition of the URL, then to understand the cross-domain is simple, cross-domain is when the protocol, sub-domain name, primary domain name, the port number of any one of the different times, the request resources will cross the domain. How to solve the cross-domain? There are three solutions, one is to rely on the background, to establish a proxy, and then through the proxy to access the resources of different domains, so that it will not cause cross-domain. There is also a more common front-end solution is to use JSONP, he is using the SRC attribute of script does not accept the principle of the same-origin policy, through the script tag to access different domain resources. First we have to write a function in our own file, and then write a function call in the requested resource. Of course we can also use the method in jquery, just add a JSONP parameter to the $.ajax parameter and assign a function name, and change the datatype to JSONP. One thing to note here, though, is that JSONP does not support the Post method because he passes the parameters via a URL.

In the new features of HTML5, there are also cross-domain solutions, just add two conditions on the server.

Header (' access-control-allow-orign:* ');

Header (' Access-control-allow-methods:post,get ');

However, this new feature is only compatible with IE10 and above versions.

Ajax Learning Notes

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.