Self-implemented ajax encapsulation example sharing

Source: Internet
Author: User

Copy codeThe Code is as follows:
// Javascript Object: ajax Object
// Created By RexLee
Function Ajax (url, data ){
This. url = url;
This. data = data;
This. browser = (function (){
If (navigator. userAgent. indexOf ("MSIE")> 0 ){
Return "MSIE"; // IE browser
} Else {
Return "other"; // other
}})();
};
Ajax. prototype = {
Get: function (){
Var result;
Var xmlhttp;
If (this. browser = 'msie '){
Try {
Xmlhttp = new ActiveXObject ('Microsoft. xmlhttp ');
} Catch (e ){
Xmlhttp = new ActiveXObject ('msxml2. xmlhttp ');
}
} Else {
Xmlhttp = new XMLHttpRequest ();
};
Xmlhttp. onreadystatechange = function (){
Result = xmlhttp. responseText; // closure, which cannot use this. Attribute
};
Xmlhttp. open ('get', this. url + '? '+ This. data, false); // true cannot capture data, why?
Xmlhttp. send (null );
Return result;
},
Post: function (){
Var result;
Var xmlhttp;
If (this. browser = 'msie '){
Xmlhttp = new ActiveXObject ('Microsoft. xmlhttp ');
} Else {
Xmlhttp = new XMLHttpRequest ();
};
Xmlhttp. onreadystatechange = function (){
Result = xmlhttp. responseText; // closure, which cannot use this. Attribute
};
Xmlhttp. open ('post', this. url, false); // It must be set to false; otherwise, responseText cannot be captured.
Xmlhttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); // in POST, this sentence must be
Xmlhttp. send (this. data );
Return result;
}
};

// Var a = new ajax ('opp2. js ','');
// Alert ('by GET \ n' + a. get ())
// Alert ('by POST \ n' + a. post ());
///////////////////////////////

 

Window. onload = function (){
Document. getElementById ("btn"). onclick = function (){
Var p = document. getElementById ("t"). value;
Var a = new Ajax ("phpOOP/getPage. php", "page =" + p );
Document. getElementById ("box"). innerHTML = a. get ();
};
}

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.