Native Js--ajax

Source: Internet
Author: User

Native Ajax:

Ajax Basics:
--ajax: No flush data read, read the information on the server
--http Request Method:
--get: Used to get data, such as browsing posts
--post: For uploading data, such as user registration


the difference between--get and post:
get:--via URL (put in URL), the passed data will be placed on the URL,--name = value & First name = value
--get mode capacity is small
--Low safety
--With cache
post:--not delivered via URL
--post Large capacity, generally up to 2G
--relatively high safety
--No cache


Native Ajax writing:
Ajax Run steps:
1. Create an Ajax object
Non-IE6 browser: var oajax=new xmlhttprequest ();
IE6 Browser: var oajax=new activexobject ("Microsoft.XMLHTTP");


2. Connect to the server
Oajax.open (method, file name, asynchronous transfer);
Block Caching methods:
Oajax.open (' GET ', ' a.txt?t= ' +new Date (). GetTime (), true);
--synchronization: JS Middle finger things have to be one thing
--Async: JS Middle finger a lot of things to do together
--ajax are asynchronous transmissions, not synchronous.


3. Sending the request
Oajax.send ();


4. Receive return value
Request Status Monitoring: onReadyStateChange event: Triggers when there is communication between Ajax and the server
mainly through the readystate attribute to determine the end of no, ended also does not represent success, the status attribute to Judge
1.--readystate Properties: Request Status
--0 (uninitialized) has not yet called the Open method
--1 (load) has called the Send () method and is sending the request
--2 (loading complete) the Send () method is complete and has received all the corresponding content
--3 (parsing) is parsing the received response content
--4 (completion) Response content resolution completed, can be called on the client (completion does not necessarily succeed, need status to detect success or failure)
2.--status Property: Request result, success (200) or failure (404): Oajax.status==200
3.--return value responsetext: Text returned from the server: Oajax.responsetext
(The returned value is a string that sometimes needs to be further processed in the form of another format)
oajax.onreadystatechange=function () {
//oajax.readystate: Indicates to which step between the browser and the server
if (oajax.readystate==4) {//Read complete
if (oajax.status==200) {//Read result is successful
alert (' success: ' +oajax.responsetext);
}
}
}


The native Ajax is encapsulated as a function, and the resulting native Ajax is:
obtn.onclick=function () {
Ajax (' data/a.txt?t= ' +new Date (). GetTime (), function (str) {
alert (str);
},function (str) {
alert (str);
});
}

//Encapsulated AJAX functions
function Ajax (url,fnsuccess,fnfaild) {
//1. Creating an Ajax Object
//js, using an undefined variable will cause an error, using an undefined attribute, is undefined
//ie6 using undefined XMLHttpRequest will result in an error, so as a property of window use
if (window. XMLHttpRequest) {
//Non-IE6
var oajax=new xmlhttprequest ();
}else{
//ie6
var oajax=new activexobject ("Microsoft.XMLHTTP");
}


2. Connect to the server
Oajax.open (' GET ', url,true);


3. Sending the request
Oajax.send ();


//4. Receiving return Values
oajax.onreadystatechange=function () {
//oajax.readystate--The browser and the server to the next step
if (oajax.readystate==4) {//Read complete
if (oajax.status==200) {//Read result is successful
fnsuccess (Oajax.responsetext);//function executed on success
}else{
If (fnfaild) {//Determine if the incoming failure is a function, that is, whether the user cares about the result of failure
Fnfaild (Oajax.responsetext); To deal with the cause of failure
}
}
}
}
}


Note * *
1--Character Set Encoding: The encoding of the Web page and the requested file is the same, If all are UTF8
2--cache, block the cache (frequently changed data, etc.) and cannot be cached. Primarily for Get methods)
 --the parameter is added after the path," + "variable data" can not affect the original data
    Ajax (' a.txt?t= ' +new Date (). GetTime (), function (str) {
       alert (str);
   },function (str) {
      alert (str);
   });


3--ajax request Dynamic Data: such as JSON file
The 3.1--ajax return value is a string that can then be read from the returned array/json data through the eval conversion
alert (str);
Alert (typeof (str));
var arr=eval (str);
Alert (typeof (arr));
Alert (arr[1]);
alert (ARR[1].C);


3.2--Create elements in conjunction with DOM to display what is returned
obtn.onclick=function () {
Ajax (' data/arr3.txt?t= ' +new Date (). GetTime (), function (str) {
var arr=eval (str);
For (var i = 0; i < arr.length; i++) {
var oli=document.createelement (' Li ');
oli.innerhtml= ' username:<span> ' +arr[i].user+ ' </span> password:<span> ' +arr[i].pass+ ' </span> ';
Oul.appendchild (oLi);
          }
},function (str) {
alert (str);
        });
      }


4--data Type-The returned data type may be XML (almost obsolete), JSON (now common)

Example: Native Ajax requesting data from a server

Data/arr3.txt: [{User: ' Blue ', pass: ' 123 '},{user: ' Red ', pass: ' 234 '},{user: ' Yellow ', pass: ' 567 '}]

1 HTML code:2<input type= "button" name= "value=" button "id=" BTN1 ">3<ul id= "ul" ></ul>4 5 6 JS Code:7<script type= "Text/javascript" >8 varObtn=document.getelementbyid (' btn1 ');9 varOul=document.getelementbyid (' ul ');Ten  Oneobtn.onclick=function(){ AAjax (' data/arr3.txt?t= ' +NewDate (). GetTime (),function(str) { -            varArr=eval (str); -             for(vari = 0; i < arr.length; i++) { the               varOli=document.createelement (' Li '); -Oli.innerhtml= ' username:<span> ' +arr[i].user+ ' </span> password:<span> ' +arr[i].pass+ ' </span> '; - Oul.appendchild (oLi); -         } +},function(str) { - alert (str); +       }); A     }; at  -  - functionAjax (Url,fnsuccess,fnfaild) { -   //1. Creating an Ajax Object -   //js, using an undefined variable will be an error, using an undefined attribute, is undefined -   //IE6 using undefined XMLHttpRequest will result in an error, so as a property of window use in   if(window. XMLHttpRequest) { -     //Non-IE6 to     varoajax=NewXMLHttpRequest (); +}Else{ -     //IE6 the     varoajax=NewActiveXObject ("Microsoft.XMLHTTP"); *   } $   //2. Connect to the serverPanax NotoginsengOajax.open (' GET ', url,true); -   //3. Sending the request the oajax.send (); +   //4. Receive return value AOajax.onreadystatechange=function(){ the     //oajax.readystate--The browser and the server to the next step +     if(oajax.readystate==4) {//Read Complete -       if(oajax.status==200) {//The result of the read is success $Fnsuccess (Oajax.responsetext);//function executed on success $}Else{ -         if(Fnfaild) {//A function that determines whether an incoming failure is the result of a user's concern about failure -Fnfaild (Oajax.responsetext);//to deal with the cause of failure the         } -       }Wuyi     } the   } - } Wu<script>

Native Js--ajax

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.