Compared with Ajax encapsulation of jquery, Yui, and some other class libraries, the Ajax of native JS is so embarrassing and has poor compatibility. remember a lot of method attributes and the call is not convenient, Code Bloated... but I still want to say that native JS is the most fundamental and bottom-layer knowledge (although I also focus on jquery Ajax in actual projects, why? Efficient !), For the elders of wood, they must fix their roots.
What Is Ajax? What are its advantages and disadvantages?
Asynchronous JavaScript and XML (Asynchronous JavaScript and XML) is a web development technology used to create interactive web applications. Simply put, it is a combination of multiple technologies. It aims to make data interaction at the front end faster and complete data updates without refreshing the page. The concept of it stops here. For more information, go to: http://zh.wikipedia.org/zh/AJAX
The advantage is obvious, which is conducive to the user experience and does not interrupt user operations. It is also a hard advantage to update content without refreshing new pages and reduce server pressure. However, in addition to the much-sought-after SEO problems, security issues, advances and retreats (although this can be solved in other ways, but the Ajax mechanism remains unchanged), damages Program The abnormal mechanism and imperfect support for emerging handheld devices are some of its shortcomings. No one is perfect, and so is Ajax. We cannot discard it because of its shortcomings.
Where do I need Ajax?
In fact, this is a too broad issue. Each project has different uses. In my experience and understanding, Ajax should be used to update data in a small area without refreshing the entire page. For example, user name or registered email data judgment, content tab content, pop-up login registration window, and feedback information after the user submits information, etc.
Practice!
Advocating thinking and practice, I firmly believe that this is an essential magic weapon to go deep into any technology. Next, I will explain the basic Ajax with a common example to verify whether users are using it. View demo
To verify the User Name Data judgment, you don't need to talk about it. It is necessary for a few front-end users to know it. The most traditional mode may be to enter information. After the user clicks submit, alert opens a window to tell the user that the xxx user name has been registered. Please enter it again! I hate the ugly Alert box! I think the same is true for most users. In this case, Ajax will be available. After the user enters the name, click (out of focus) anywhere outside the form, and Ajax will quickly report the information entered by the user to the server for judgment, then, a message is returned to inform the user of whether the entered nickname is available. In this case, we need a front-end input form with the Code as follows:
In addition, we also need a back-end page to determine whether the input nickname exists (this article uses PHP as an example, this part does not need to be detailed ):
... If (isset ($ _ Get ['entryname']) {$ entryname = $ _ Get ['entryname'];} else {$ entryname = 'data null ';} $ SQL = sprintf ("select * From I _test_ajax where nickname = '% S'", $ entryname); $ res = $ iajax-> query ($ SQL ); // sleep is only used to show the effect of sleep (1) When readstate = 1; if ($ res-> num_rows)> 0) {echo "Sorry! This nickname already exists: (";} else {echo" Congratulations! This nickname can be registered :)";}...
In this way, everything is ready, and the rest is handed over to Ajax for processing.
XMLHttpRequest is an object that has to be mentioned. The core of AJAX is also the underlying object. Sadly, it is a W3C standard, but Microsoft IE has always been very self (Microsoft IE ). What should I do? Of course, they are harmonious in one way. Microsoft IE supports activexobject ('Microsoft. xmlhttp') objects, which is simple:
// Compatible XMLHTTPRequest object ixhr: function () {If (window. activexobject) {xhr = new activexobject ('Microsoft. XMLHTTP ');} else if (window. XMLHttpRequest) {xhr = new XMLHttpRequest () ;}else {return NULL ;}}
The compatible XMLHTTPRequest object is implemented. Next, write a simple onblur event, that is, when the input value expires, the form starts to judge and return a message to the foreground quickly. The Code is as follows:
// Execute document when triggering the focus. forms ['form']. nickname. onblur = function () {// input value var val = document. forms ['form']. nickname. value; // user name judgment if (! /^ [A-zA-Z0-9 _] {3, 16} $/. Test (VAL) {alert ('enter 3 ~ A 16-digit nickname with English letters, numbers, and underscores! '); Return false;} // initialize xhr IBASE. ixhr (); // use get to use Asynchronous xhr. open ('get', '/demo/ajax/iajax20110306_query.php? Entryname = '+ val, true); // It is related to the readystate attribute. xhr is triggered only when readystate is changed. onreadystatechange = returnfun; // send data after asynchronous processing is completed (for example, some tasks that need to be executed after the focus event) xhr. send (null );}
Explain the Ajax code. IBase. ixhr (), initialize xhr to ensure compatibility with XMLHttpRequest objects. Next, you can use the get method to asynchronously send to the/demo/ajax/iajax20110306_query.php page for verification. Someone may ask what is get and get requests data from the server. The get method is to add the data parameter queue to a URL, and the values correspond to the forms one by one, for example, entryname = Val in this article. This concept may fall within the scope of background programs. Then, we need to use an onreadystatechange event attribute, which is used to store functions (or function names). When the readystate attribute changes, this function is called, that is, returnfun in this article; finally, we need to send a data to the server. The send attribute is generally used for data exchange. This article is just a simple verification and judgment. Therefore, send a null value.
The basic judgment and data transmission are complete, and a key information is available, that is, returnfun. First look at the Code:
function returnfun () {// when send () has been called and the request is being sent, the loading... if (xhr. readystate = 1) {IBASE. ID ('tids '). innerhtml = 'loding... ';} else if (xhr. readystate = 4) {// when the response content is parsed, you can call it // more carefully, and then determine whether the status is successful if (xhr. status = 200) {// responsetext is the returned text IBASE. ID ('tids '). innerhtml = xhr. responsetext;} // destroy after use to avoid Memory leakage xhr = NULL ;}
This function is used to timely feedback the user's prompt information by judging the readystate and status. Readystate has five states:
0 (not initialized): (XMLHttpRequest) the object has been created, but the open () method has not been called;
1 (load): the open () method has been called, but no request has been sent;
2 (Loading completed): The request has been sent;
3 (interaction): Some response data can be received;
4 (complete): All data has been received and the connection has been closed.
In this way, you should be able to understand the readystate function, and the status is actually a secondary State judgment, but the status is mostly the server state judgment. About status, as there are dozens of statuses, I only list the common ones:
100 -- the customer must continue to send the request
101 -- the client requests the server to convert the HTTP protocol version according to the request
200 -- successful
201 -- prompt to know the URL of the new file
300 -- the requested resources can be obtained in multiple places
301 -- Delete request data
404 -- no file, query, or URL found
500 -- Internal error occurred on the server
So far, a simple Ajax verification instance has been completed:View demo
There are so many basic Ajax introductions and examples, the key lies in your own practice and thinking. In fact, the knowledge involved in this process is not complex. If you have the foundation of backend programs, it is easier to learn Ajax. The key is to understand the logical relationship. If you are interested, you can write an Ajax script that loads new content without refreshing a new page, or study Ajax encapsulation in jquery.
Blog published in mr. Think: http://mrthink.net/ajax-starter-xmlhttpreq/ reprint please note