标签:seh 停止 方式 ica false 返回 post 类型 async
/*** Created by liyinghao on 2016/8/23.*//*仿jQuery中的ajax方法,简单版实现;封装ajax的工具函数*//** 1 请求方式 type get post 默认是get方式* 2.接口地址 url 都是地址 默认的是当前地址* 3.是否异步 async true false 默认的true 异步请求* 4.请求数据 data {}对象形式 默认是空对象*** 5.成功回调函数(成功需要做的事情) success* 6.失败回调函数(失败需要做的事情) error** 比如 发送前要做的事情 beforeSend* */window.$ ={/* ajax:function(){}*/};/*定义一个ajax工具函数*//*options 是一个对象*/$.ajax = function(options){/*如果你什么都没传呢?停止执行*//*if(options && typeof options == ‘object‘){}*/if(!options || typeof options != ‘object‘) return fasle;/*如果传了*/var type = options.type || ‘get‘;var url = options.url || location.pathname;/* false true "" false */var async = options.async === false ? false : true;/*需要传递的数据*/var data = options.data || {};/*需要data转化成ajax传递数据的格式 {name:‘‘,age:‘‘} ===>>> name=gc&age=10 */var dataStr = ‘‘;for(key in data){dataStr += key+‘=‘+data[key]+‘&‘;};/*str.slice(0,-1); 取到倒着数几个字符*/dataStr = dataStr && dataStr.slice(0,-1);/*ajax编程*//*初始化*/var xhr = new XMLHttpRequest();/*设置请求行*//*如果是get请求 参数是不是该拼接在url后面*/xhr.open(type,type==‘get‘?url+‘?‘+dataStr:url,async);/*设置请求头*/if(type == ‘post‘){xhr.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded‘);}/*设置请求内容*/xhr.send(type==‘get‘?null:dataStr);/*响应*/xhr.onreadystatechange = function(){/*首先确定通讯完全完成*/if(xhr.readyState == 4){/*如果是成功的请求 status == 200 */if(xhr.status == 200){/*成功*//*知道后台想要返回什么数据类型 application/json;charset=utf-8*//*application/xml application/json text/html text/xml text/json text/css*/var contentType = xhr.getResponseHeader(‘Content-Type‘);var result = null;if(contentType.indexOf(‘xml‘) > -1){/*返回什么数据类型xml*/result = xhr.responseXML;}else if(contentType.indexOf(‘json‘) > -1){/*返回什么数据类型json*/var data = xhr.responseText;result = data && JSON.parse(data);}else{result = xhr.responseText;}/*执行成功回调函数*/options.success && options.success(result);}else{/*失败*/options.error && options.error({status:xhr.status,statusText:xhr.statusText});}}}};/*get*/$.get = function(options){options.type = ‘get‘;$.ajax(options);}/*post*/$.post = function(options){options.type = ‘post‘;$.ajax(options);}
标签:seh 停止 方式 ica false 返回 post 类型 async
原文地址:http://www.cnblogs.com/itlyh/p/6031362.html