This article mainly and everyone to share the AJAX simple package detailed introduction, hope to be able to help you.
Ajax is generally divided into four simple parts:
Create an Ajax object (this is compatible with IE to do a bit of processing)
Connection, that is, the open method of the Request object (get and post are also a bit different, get parameters to be placed behind the URL, post to set the request header)
Send, which is the send function of the request object (the post parameter is placed in send)
Receive, the function is called when the onreadystatechange (stored function or function name, whenever the ReadyState property changes. ) function inside the process.
You can also add timeouts to these
onReadyStateChange Analysis
To determine the state of the readystate first (there are four states)
①: 0, request uninitialized;
②: 1, the server connection has been established;
③: 2, the request has been received;
④: 3, request processing;
⑤: 4, the request is complete and the response is ready
When readystate equals 4 o'clock, you have to judge status.
When the request succeeds, status state 200-302, and 304 (cache)
' Use strict '; var $ = {};$.ajax = ajax;function Ajax (options) {//parse parameter options = Options | | {}; if (!options.url) return; Options.type = Options.type | | ' Get '; Options.timeout = Options.timeout | | 0; 1 Create an Ajax if (window. XMLHttpRequest) {//Advanced browser and IE7 above var xhr = new XMLHttpRequest (); } else {//ie6,7,8 var xhr = new ActiveXObject ("Microsoft.XMLHTTP"); }//2 connection var str = jsontourl (options.data); if (Options.type = = = ' Get ') {xhr.open (' get ', ' ${options.url}?${str} ', true); 3 send Xhr.send (); } else {Xhr.open (' post ', Options.url, true); Request Header Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); 3 send Xhr.send (); }//Receive Xhr.onreadystatechange = function () {//complete if (xhr.readystate = = = 4) {//Clear timer cleartimeout (ti MER); if (xhr.status >= && Xhr.status < | | xhr.status = 304) {//Success options.success && Amp Options.success (Xhr.responsetext); }else {options.error && options.error (xhr.status); } } }; Timeout if (options.timeout) {var timer = setTimeout (function () {alert ("timed out"); Xhr.abort (); termination of},options.timeout); }}//JSON to Urlfunction Jsontourl (JSON) {var arr = []; json.t = Math.random (); for (var name in JSON) {Arr.push (name + ' = ' + encodeURIComponent (Json[name])); } return Arr.join (' & ');}