我一直在尝试创建一个没有jQuery或任何其他库的纯函数来在ajax请求中转换我的web应用程序上的所有链接。但正如你应该知道的那样没有成功。
有人能告诉我哪里出错了吗?
function ajaxify() {
var content = document.getElementsByTagName('body');
var links = document.body.querySelectorAll('a');
[].forEach.call(links, function (link) {
console.log(link);
link.addEventListener('click', function (event) {
var url = link.href;
// Manipulate history
window.history.pushState({}, '', url);
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function () {
if (request.status == 200) {
content[0].innerHTML = request.responseText;
} else {
alert('Request failed. Returned status of' + request.status);
}
};
request.send();
event.preventDefault();
});
});
}
修改
以上脚本之一的页面不起作用
Web APP© 2016 - Web APP
ajaxify();
解决
唯一的问题是XMLHttpRequest出于安全原因不允许将脚本作为DOM文本发送。所以我放弃了,现在我正在使用jQuery来做到这一点。 :(