前言
最近写博客真的是太痛苦了,倒不是写博客本身,而是写完之后往多个平台发布的过程,一不注意就是十多分钟往上的时间消耗。
为了解决这个问题,之前立项的“解决自媒体一键多平台发布”项目必须得立刻着手完善了,争取早日让自己从发布这件事情上解脱出来专心写文章。
【hxsfx的JavaScript库】这个系列基本上是为“一键多平台发布”项目打基础用的。之所以把各个功能模块拆分出来,是为了尽量让小伙伴能够复制即用(在兼容性方面,因为个人能力的原因,几乎只会兼容Chrome浏览器)。
hxsfx.ajax库
(一)介绍
AJAX 是异步的 JavaScript 和 XML(Asynchronous JavaScript And XML),开发hxsfx.ajax库的主要目的就是希望通过异步加载HTML,从而尽量避免直接在js中写HTML来刷新页面内容。
hxsfx.ajax这个库与jquery的ajax功能基本一致,不过短时间内应该是写不到人家那么完善的。哈哈~
各位小伙伴别问,为什么不用jquery的ajax而要自己再写一个呢?
问就是,博主喜欢造轮子。开玩笑了~
其实原因是为了减少三方库的依赖,达到对项目的全面掌控。
项目地址:https://github.com/hxsfx/hxsfx_web_tools
(二)代码
要自己开发一个ajax库,需要借助Web API接口中的XMLHttpRequest(XHR)对象。
XMLHttpRequest(XHR)对象用于与服务器交互。通过 XMLHttpRequest 可以在不刷新页面的情况下请求特定 URL,获取数据。这允许网页在不影响用户操作的情况下,更新页面的局部内容。
1、在window对象上新建一个hxsfx对象,本系列的所有库基本都会在hxsfx对象之中:
//hxsfx.js(function () { window.hxsfx = {};})();2、在hxsfx对象的基础上新建一个ajax对象:
//ajax.js(function () { window.hxsfx.ajax = { };})();3、在ajax对象中新建loadHTML方法,设置两个参数,分别是ele准备加载HTML的容器元素和url加载HTML的地址:
//ajax.js(function () { window.hxsfx.ajax = { loadHTML: function (ele, url) { } };})();4、在loadHTML方法中新建XMLHttpRequest对象:
//ajax.js(function () { window.hxsfx.ajax = { loadHTML: function (ele, url) { const httpRequest = new XMLHttpRequest(); httpRequest.open('GET', url, true); httpRequest.onreadystatechange = function () { //为了让代码更健壮,使用try...catch来捕获返回状态判断和处理HTML代码的异常 try { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { //在这处理返回的HTML } } else { console.log("【ajax.get(" + url + ")请求出错】"); } } } catch (ex) { console.log("【ajax.get(" + url + ")异常】" + ex.message); } }; httpRequest.s(); } };})();5、为了解决加载HTML缓存的问题,将loadHTML方法中传入的URL参数后面加上一个时间戳:
//ajax.js//时间戳用来解决加载页面缓存的问题var urlTimeStamp = "timeStamp=" + new Date().getTime();url += ((url.indexOf('?') >= 0) ? "&" : "?") + urlTimeStamp;6、【重点】在这处理返回的HTML时,如果直接将HTML加载到容器中,会出现HTML中Javascript代码不执行的问题。解决这个问题,需要将加载的script标签替换为script元素:
//ajax.jsele.innerHTML = httpRequest.responseText;var scriptElements = ele.getElementsByTagName("script");for (var i = 0; i < scriptElements.length; i++) { var scriptElement = document.createElement("script"); scriptElement.setAttribute("type", "text/javascript"); var src = scriptElements[i].getAttribute("src"); if (src) { //因为加载的src路径是之前相对加载HTML页面的,需要修改为当前页面的引用路径 src = url.substring(0, url.lastIndexOf('/') + 1) + src; src += ((src.indexOf('?') >= 0) ? "&" : "?") + urlTimeStamp; scriptElement.setAttribute("src", src); } var scriptContent = scriptElements[i].innerHTML; if (scriptContent) { scriptElement.innerHTML = scriptContent; } //用生成的script元素去替换html中的script标签,以此来激活script代码 ele.replaceChild(scriptElement, scriptElements[i]);}7、最后ajax.js完整代码:
//ajax.js(function () { window.hxsfx.ajax = { loadHTML: function (ele, url) { //时间戳用来解决加载页面缓存的问题 var urlTimeStamp = "timeStamp=" + new Date().getTime(); url += ((url.indexOf('?') >= 0) ? "&" : "?") + urlTimeStamp; const httpRequest = new XMLHttpRequest(); httpRequest.open('GET', url, true); httpRequest.onreadystatechange = function () { //为了让代码更健壮,使用try...catch来捕获返回状态判断和处理HTML代码的异常 try { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { ele.innerHTML = httpRequest.responseText; var scriptElements = ele.getElementsByTagName("script"); for (var i = 0; i < scriptElements.length; i++) { var scriptElement = document.createElement("script"); scriptElement.setAttribute("type", "text/javascript"); var src = scriptElements[i].getAttribute("src"); if (src) { //因为加载的src路径是之前相对加载HTML页面的,需要修改为当前页 src = url.substring(0, url.lastIndexOf('/') + 1) + src; src += ((src.indexOf('?') >= 0) ? "&" : "?") + urlTimeStamp; scriptElement.setAttribute("src", src); } var scriptContent = scriptElements[i].innerHTML; if (scriptContent) { scriptElement.innerHTML = scriptContent; } //用生成的script元素去替换html中的script标签,以此来激活script代 ele.replaceChild(scriptElement, scriptElements[i]); } } } else { console.log("【ajax.get(" + url + ")请求出错】"); } } } catch (ex) { console.log("【ajax.get(" + url + ")异常】" + ex.message); } }; httpRequest.s(); } };})();(三)调用文档
1、将hxsfx.js和ajax.js放入Scripts文件夹中的hxsfx文件夹
2、在Scripts文件夹同级目录新建index.html页面
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>js库测试</title> <script src="Scripts/hxsfx/hxsfx.js"></script> <script src="Scripts/hxsfx/ajax.js"></script> <script> window.onload = function () { //调用ajax中的loadHTML方法 window.hxsfx.ajax.loadHTML(document.getElementById("ContentContainer"), "Views/test/testPage.html"); }; </script></head><body> <p id="ContentContainer"></p></body></html>3、在Scripts文件夹同级目录,首先新建Views文件夹,接着其中新建test文件夹,最后在test文件夹中新建testPage.html
<style> p#TestPageContainer { height: 300px; width: 300px; background-color: #F0F0F0; }</style><script src="../../Scripts/hxsfx/test/test.js"></script><script> function updateBackgroundColor() { try { var backgroundColor = '#' + (Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')); document.getElementById("TestPageContainer").style.backgroundColor = backgroundColor; } catch (ex) { console.log(ex.message); } }</script><p id="TestPageContainer"> <button onclick="updateBackgroundColor()">更改背景色</button> <button onclick="modifyPFontColor()">更改下面一句话的字体颜色</button> <p id="P">这儿是一句话。</p></p>
最后
以上内容只是hxsfx.ajax库的开始,后续的内容更新小伙伴可以通过访问Github项目地址进行获取。