[{"data":1,"prerenderedAt":60},["ShallowReactive",2],{"blog-post-2016-02-03-e5-9f-ba-e4-ba-8e-es6-promise-e7-9a-84-ajax-e5-b0-81-e8-a3-85":3},{"id":4,"title":5,"body":6,"categories":47,"date":49,"description":12,"extension":50,"meta":51,"navigation":52,"path":53,"seo":54,"stem":55,"summary":56,"tags":57,"__hash__":59},"blog\u002Fblog\u002Fe5-9f-ba-e4-ba-8e-es6-promise-e7-9a-84-ajax-e5-b0-81-e8-a3-85.md","基于 ES6 Promise 的 AJAX 简单封装",{"type":7,"value":8,"toc":44},"minimark",[9,13,24],[10,11,12],"p",{},"基于 Promise 的 ajax 请求，可以实现链式调用，使代码结构更清晰，代码如下：",[14,15,20],"pre",{"className":16,"code":18,"language":19},[17],"language-text","'use strict';\n\u002F\u002F 函数封装\nvar handleAjax = function handleAjax() {\n  var options = arguments.length \u003C= 0 || arguments\\[0\\] === undefined ? {} : arguments\\[0\\],\n  opt = {\n    url: options.url || '',\n    data: options.data || 't=' + new Date().getTime(),\n    type: options.type || 'get',\n    dataType: options.dataType || 'json',\n    cache: options.cache || false,\n    async: options.async || true,\n    context: options.context || document.body,\n    beforeSend: options.beforeSend || undefined\n  };\n  return new Promise(function (resolve, reject) {\n    var req = new XMLHttpRequest();\n    if (typeof opt.beforeSend === 'function') {\n      opt.beforeSend();\n    }\n    req.open(opt.type, opt.url, opt.async);\n    req.onload = function () {\n      if (req.status === 200) {\n        var data = req.responseText;\n        if (opt.dataType === 'json') {\n          data = JSON.parse(data);\n        }\n        resolve(data);\n      } else {\n        reject(new Error(req.statusText || 'You can\\\\'t do this.'));\n      }\n    };\n    req.onerror = function () {\n      reject(new Error(req.statusText || 'Server is down.'));\n    };\n    req.send();\n  });\n};\n\u002F\u002F 调用函数\nvar options = {\n  url: 'http:\u002F\u002Fhttpbin.org\u002Fget'\n};\nhandleAjax(options).then(function (data) {\n  console.log(data);\n})\\['catch'\\](function (error) {\n  console.log(error);\n});\n","text",[21,22,18],"code",{"__ignoreMap":23},"",[10,25,26,33,34,33,39],{},[27,28,32],"a",{"href":29,"rel":30},"http:\u002F\u002Fcodepen.io\u002Finterjc\u002Fpen\u002FdGjeVm?editors=0012",[31],"nofollow","预览效果"," | ",[27,35,38],{"href":36,"rel":37},"https:\u002F\u002Fgist.github.com\u002Finterjc\u002F53f574fc6d7c67b98046",[31],"源码",[27,40,43],{"href":41,"rel":42},"http:\u002F\u002Fliubin.org\u002Fpromises-book\u002F",[31],"参考资料",{"title":23,"searchDepth":45,"depth":45,"links":46},2,[],[48],"Development","2016-02-03T09:54:02+08:00","md",{},true,"\u002Fblog\u002Fe5-9f-ba-e4-ba-8e-es6-promise-e7-9a-84-ajax-e5-b0-81-e8-a3-85",{"title":5,"description":12},"blog\u002Fe5-9f-ba-e4-ba-8e-es6-promise-e7-9a-84-ajax-e5-b0-81-e8-a3-85","基于 Promise 的 ajax 请求，可以实现链式调用，使代码结构更清晰，代码如下： 预览效果 | 源码 | 参考资料",[58],"javascript","Ybn-LE8Hk_Ll06JZTpB3CTWgOC4m-jUQhf4-9WWuA7E",1795177971899]