Ajax under JavaScript

Source: Internet
Author: User

/**
* Perform basic AJAX request, return XMLHttpRequest
* Ajax.request ({
* URL
* Async is Async true (default)
* Method Request Mode POST or GET (default)
* Data Request parameter (key-value pair string)
* Success Response function After successful request, parameter is XHR
* Response function after error request failed, parameter is XHR
*  });
*/
Ajax = function () {
function request (OPT) {
function fn () {
}
var url = Opt.url | | "";
var async = Opt.async!== false, method = Opt.method | | ' GET ', data = Opt.data
|| NULL, success = Opt.success | | FN, error = Opt.failure
|| fn
method = Method.touppercase ();
if (method = = ' GET ' && data) {
var args = "";
if (typeof data = = ' string ') {
Alert ("string")
args = data;
}else if (typeof data = = ' object ') {
Alert ("Object")
var arr = new Array ();
For (var k in data) {
var v = data[k];
Arr.push (k + "=" + V);
}
args = Arr.join ("&");
}
URL + = (url.indexof ('? ') = =-1? '? ': ' & ') + args;
data = null;
}
var xhr = window. XMLHttpRequest? New XMLHttpRequest ()
: New ActiveXObject (' microsoft.xmlhttp ');
Xhr.onreadystatechange = function () {
_onstatechange (XHR, success, error);
};
Xhr.open (method, URL, async);
if (method = = ' POST ') {
Xhr.setrequestheader (' Content-type ',
' application/x-www-form-urlencoded; ');
}
Xhr.send (data);
return XHR;
}
function _onstatechange (XHR, success, failure) {
if (xhr.readystate = = 4) {
var s = xhr.status;
if (s >= && s < 300) {
Success (XHR);
} else {
Failure (XHR);
}
} else {
}
}
return {
Request:request
};
}();

Ajax under JavaScript

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.