/**
* ITCAST WEB
* Created by zhousg on 2016/5/24.
*/
/*
* 1. 请求的类型 type get post
* 2. 请求地址 url
* 3. 是异步的还是同步的 async false true
* 4. 传输的数据 data json对象
*
* 5.响应成功处理函数 success function
* 6.响应失败的处理函数 error function
*
* 这些都是动态参数 参数对象 options
* */ /*封装一个函数*/
window.$ = {};
/*申明一个ajax的方法*/
$.ajax = function(options){ if(!options || typeof options != 'object'){
return false;
} /*请求的类型*/
var type = options.type || 'get';/*默认get*/
/*请求地址 */
var url = options.url || location.pathname;/*当前的地址*/
/*是异步的还是同步的 */
var async = (options.async === false)?false:true;/*默认异步*/
/*请求内容的格式 */
var contentType = options.contentType || "text/html"; /*传输的数据 */
var data = options.data || {};/*{name:'',age:''}*/
/*在提交的时候需要转成 name=xjj 这种格式*/ var dataStr = ''/*数据字符串*/ for(var key in data){
dataStr += key+'='+data[key]+'&';
} dataStr = dataStr && dataStr.slice(0,-1); /*ajax 编程*/
var xhr = new XMLHttpRequest(); /*请求行*/
/*(type=='get'?url+'?'+dataStr: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 && xhr.status == 200){
/*success*/
var data = '';
var contentType = xhr.getResponseHeader('Content-Type');
/*如果我们服务器返回的是xml*/
if(contentType.indexOf('xml') > -1){
data = xhr.responseXML;
}
/*如果我们的服务器返回的是json字符串*/
else if(contentType.indexOf('json') > -1){
/*转化json对象*/
data = JSON.parse(xhr.responseText);
}
/*否则的话他就是字符串*/
else{
data = xhr.responseText;
} /*回调 成功处理函数*/ options.success && options.success(data);
}
/*计时请求xhr.status不成功 他也需要的响应完成才认作是一个错误的请求*/
else if(xhr.readyState == 4){
/*error*/
options.error && options.error('you request fail !'); } }
}
$.post = function(options){
options.type = 'post';
$.ajax(options);
}
$.get = function(options){
options.type = 'get';
$.ajax(options);
}

最新文章

  1. 常见的java类
  2. C#子类调用基类构造备忘
  3. usb驱动开发16之设备生命线
  4. AspCms标签手册
  5. Android事件分发机制(二)30分钟弄明白Touch事件分发机制
  6. Babelfish 分类: 哈希 2015-08-04 09:25 2人阅读 评论(0) 收藏
  7. php 未配置curl
  8. First Lua function running in C
  9. Android实例-读取设备联系人(XE8+小米2)
  10. JS定义对象方法?
  11. 乘积最大洛谷p1018
  12. 用vlc搭建简单流媒体服务器(UDP和TCP方式)
  13. css3兼容360
  14. c# 对象集合转Json
  15. 五、django rest_framework源码之版本控制剖析
  16. underscore.js源码解析(五)—— 完结篇
  17. Ubuntu 16.04 compare 软件安装
  18. IOS开发错误
  19. python__标准库 : urllib2
  20. 转:USB枚举

热门文章

  1. 【C++第三课】---新的关键字
  2. RMAN备份各种物理文件
  3. 阿里云RDS导入服务器数据库 XtraBackup
  4. tomcat https jks 沃通免费证书安装 解决方案
  5. (Access denied for user 'root'@'localhost' (using password: NO))
  6. vector 汇总
  7. MySTLString
  8. VS 2013驱动开发 + Windbg + VM双机调试(亲测+详解)
  9. ORA-04092: COMMIT 不能在触发器中
  10. ios html5 长按复制文本