1.创建一个AJAX引擎对象
1 var CreateAjax = function () { 2 var xhr = null; 3 4 if (window.XMLHttpRequest) 5 { 6 //非IE游览器 7 xhr=new XMLHttpRequest(); 8 }else 9 { 10 //IE游览器 11 xhr = new ActiveXObject("Microsoft.XMLHTTP"); 12 } 13 return xhr; 14 };
2.创建一个全局对象
var Ajax = function (option) { //初始化数据 //可选GET,POST var type = option.type; //请求地址 var url = option.url; var data = option.data; //返回数据类型 var dataType = option.dataType; //是否异步 var async = option.async; var success = option.success; //默认为GET方式 if(type==null){ type = "GET"; } //默认返回文本类型 if (dataType == null) { dataType = "text"; } if (async == null) { async = true; } //创建XMLHttpRequest对象 var xhr = CreateAjax(); //打开 xhr.open(type, url, async); //发送 if (type == "GET" || type == "get") { xhr.send(null); } else if (type == "POST" || type == "post") { xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); xhr.send(data); } xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { if (dataType == "TEXT" || dataType == "text") { if (success != null) { success(xhr.responseText); } else if (dataType == "xml" || dataType == "XML") { success(xhr.responseXML); } else if (dataType == "json" || dataType == "JSON") { success(eval("(" + xhr.responseText + ")")); } } } }; };
3.调用方式
1 Ajax({ 2 type: "POST", 3 url: "LoginHandler.ashx", 4 data: "userName="+userName.value+"&password="+password.value, 5 dataType:"text", 6 7 success: function (data) { 8 alert(data); 9 } 10 11 });
简单了封装一下,能基本满足需求..可进行扩充
原文:http://www.cnblogs.com/aasd147789/p/4982166.html