From f795667b5b96559d87f9c32e03fce5db33f13937 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=87=E5=A4=A9?= Date: Mon, 9 Sep 2019 20:18:17 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9B=A0=E4=B8=BA=E4=B8=8D=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E5=8D=8F=E8=AE=AE=E7=9A=84=E7=BC=98?= =?UTF-8?q?=E6=95=85,=E6=94=BE=E5=BC=83fetch=E7=9A=84=E4=BD=BF=E7=94=A8,?= =?UTF-8?q?=E6=94=B9=E5=9B=9Exhr?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- src/26-:include.js | 42 ++++++++++++++++++++++++++---------------- 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/package.json b/package.json index c511692..3143b83 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "anot", - "version": "2.2.0", + "version": "2.2.1", "description": "Anot - 迷你mvvm框架", "main": "dist/anot.js", "files": ["dist"], diff --git a/src/26-:include.js b/src/26-:include.js index 52b8271..c29926d 100644 --- a/src/26-:include.js +++ b/src/26-:include.js @@ -20,6 +20,26 @@ function nodesToFrag(nodes) { } return frag } + +function _fetch(url) { + var xhr = new XMLHttpRequest() + var defer = Promise.defer() + xhr.open('GET', url, true) + xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest') + xhr.responseType = 'text' + xhr.onreadystatechange = function() { + if (this.readyState === 4) { + if (this.status >= 200 && this.status < 400) { + defer.resolve(this.response) + } else { + defer.reject(this) + } + } + } + xhr.send(null) + return defer.promise +} + Anot.directive('include', { init: directives.attr.init, update: function(val) { @@ -141,27 +161,17 @@ Anot.directive('include', { scanTemplate(templatePool[val]) }) } else { - fetch(val, { - method: 'get', - headers: { - 'X-Requested-With': 'XMLHttpRequest' - } - }) - .then(res => { - if (res.status >= 200 && res.status < 300) { - return res.text() - } else { - return Promise.reject( - `获取网络资源出错, ${res.status} (${res.statusText})` - ) - } - }) + _fetch(val) .then(text => { templatePool[val] = text scanTemplate(text) }) .catch(err => { - log(':include load [' + val + '] error\n%c%s', 'color:#f30', err) + log( + ':include load [' + val + '] error\n%c%s', + 'color:#f30', + `获取网络资源出错, ${err.status} (${err.statusText})` + ) }) } }