原生js 的ajax封装
/**
* 封装ajax函数(包括跨域)
* @method ajax
* @param option :{type:"post" or "get" 请求方式,url:"url" 请求地址,data:object 请求参数,async:"true" 异步or“false”同步,success:function 请求成功回调函数,error:function,请求失败函数,jsonp:"true" 表示跨域 “false”:表示不跨域;callback:function 跨域请求函数名}
* @return {}
*
*/
function ajax(option) {
"use strict";
//检测传入参数是否是一个对象
if ({}.__proto__.toString.call(option) !== "[object Object]") {
alert("参数格式错误!!");
return;
}
var data = option.data || "";
var async = option.async || "true";//默认是异步
var jsonp = option.jsonp || "false"//默认是不跨域http
var params=[];
var postData;
var getHttpRequest = function () {
if (window.XMLHttpRequest) {
//主流浏览器提供了XMLHttpRequest对象
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
//低版本的IE浏览器没有提供XMLHttpRequest对象
//所以必须使用IE浏览器的特定实现ActiveXObject
return new ActiveXObject("Microsoft.XMLHttpRequest");
}
};
if(data!==""){
for (var key in data) {
params.push(key + '=' + data[key]);
}
}
postData= params.join('&');
if (jsonp !== "true") {//不是跨域
var httpRequest = getHttpRequest();
if (option.type.toUpperCase() === 'POST') {
httpRequest.open(option.type, option.url, async);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
httpRequest.send(postData); }
else if (option.type.toUpperCase() === 'GET') {
httpRequest.open(option.type, option.url + '?' + postData, async);
httpRequest.send(null);
}
httpRequest.onreadystatechange=function(){
if(httpRequest.readyState==="4"&&httpRequest.state==="200"){
option.success(httpRequest.responseTest); }else{
option.error(httpRequest.responseTest);
} }
} else { //跨域
var responseContainer;
var overwritten;
var doc=document.body;
var _script=document.createElement("script");
_script.setAttribute("type","text/javascript");
_script.src=option.url+"?"+postData+"&callback="+option.callback;
doc.appendChild(_script);
overwritten=window[option.callback];
window[option.callback]=function(){
responseContainer= arguments; }
option.success(responseContainer[0]);
responseContainer = overwritten = undefined; }}
人活着,最重要的就是开心