ajax入门

71 阅读1分钟
  • Asynchronous JavaScript and XML 异步的javascript和XML
  • 不刷新页面的情况下js异步发送http请求数据,返回json等数据,让前后端分离有可能

创建xhr对象

var xhr;
if(window.XMLHttpRequest) {
 xhr = new XMLHttpRequest();
}else {
// ie5/ie6兼容性
 xhr = new ActiveXObject('MicrosoftXMLHTTP');
}

open方法

  • option参数列表
    method: 请求方式
    url: 请求地址
    async: true异步,false同步
  • send方法:发送请求 参数:发生POST请求体数据用,GET不用写
xhr.open('GET', 'https;//www.baidu.com', true);
xhr.send(); 
// post : 
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');  // 目的是请求体后的数值转换为键值对。服务器知道是post方式
 // xhr.send('a=1&b=2');

AJAX-发送请求时的响应任务

onreadystatechange 事件:挂载到XMLHttpRequest对象 上的事件 readyState 状态:通过XMHttpRequest对象 发送HTTP请求的各阶段状态码(0-4)
status 状态:服务器响应的状态码(200 OK、404 未拽到页面) 当readyState变化时,将触发onreadystatechange 事件执行其回调函数(2,3,4) 0:请求未初始化,创建后,发送前 1:服务器连接已建立,发送后 2:请求已接收 3:请求处理中 4:请求已完成,且响应已就绪 注意:readyState仅仅是针对请求的状态码,获取资源是否成功取决于status的状态。

xhr.onreadystatechange = function() {
 if(xhr.readyState === 4 && xhr.status === 200) {
  console.log(JSON.parse(xhr.responseText));  // 返回json的字符串对象
 }
}

服务器相应

responseText: 获取字符串数据
responseXML:获取XML数据

封装ajax

var $ = (function() {
 var xhr = window.XMLHttpRequest ? 
                  new XMLHttpRequest :
                  new ActiveXObject('Miscrosoft.XMLHTTP');
 if(!xhr) {
  throw new Error('您的浏览器不支持ajax');
 }
function _doAjax(opt) {
 var opt = opt || {},
        type = (opt.type || 'GET').toLowerCase(),
        async = opt.async || true,
        url = opt.url,
        data = opt.data || null,
        error = opt.error || function() {},
        success =opt.success || function() {},
        complete = opt.complete || function() {};  // 不管成功失败都执行
if (!url) {
 throw new Error('没有配置url');
 }
xhr.open(type, url, async);
type === 'POST' && xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencode');
xhr.send(type === 'GET' ? null : formatData(data));
xhr.onreadystatechange = function() {
 if(xhr.readyState === 4 && xhr.status === 200) {
  success(JSON.parse(responseText));
 }
 if(xhr.status === 404) {
  error();
 }
 complete();
}
 
}
function formatData(obj) {
 var str = '';
 for(var key in obj) {
  str += key + '=' + obj[key] + '&';
 }
 return str.replace(/&$/, '');
}
return {
 ajax: function(opt) {
// 在外面定义函数就可以接收参数了
  _doAjax(opt);
 },
 post: function(url, data, callback) {
  _doAjax({
    type: 'POST',
    url: url,
    data: data,
    success: callback
  });
 }
 get: function(url, callback) {
_doAjax({
    type: 'GET',
    url: url,
    success: callback
  });
 }
}
})();