如何在AJAX请求上加载脚本? [英] How to load Scripts on AJAX requests?
问题描述
我正在尝试制作SPA网站。
I'm trying to make a SPA web.
显然,如果我在元素的innerHTML上加载带有AJAX的内容,那么脚本AJAX内容中的
标签无效。
Apparently if i load content with AJAX on the innerHTML of an element, the script
tag in the AJAX content won't work.
问题是我需要在AJAX内容中再制作一个AJAX请求。
我不能只使用基本模板的JavaScript代码,因为在初始页面加载时,我将事件绑定到元素,AJAX内容未加载,因此没有绑定。
The problem is that i need to make another AJAX request in the AJAX content. I can't just use the JavaScript code of the base template because at the initial page loading, where i bind the events to the elements, the AJAX content is not loaded, so no binding.
STRUCTURE
基本上我想做的是:
STRUCTURE Basically what i want to do is this:
基本模板:它有一个导航栏,可以在名为 ajaxContent
的div上加载AJAX内容,链接产品, 常见问题和关于我们在div 上加载相应的模板
。 products.html
... ajaxContent
Base Template: it has a navigation bar that loads AJAX content on a div called ajaxContent
, the links Products, FAQ and About Us load the respective templates products.html
... on the div ajaxContent
.
产品模板:这是产品目录,其中有另一个带有类别名称的导航栏,它应该与基本模板中的nav类似:在名为 AjaxCatalog
的div中加载AJAX内容,但是我无法在此模板中发出AJAX请求,因为 script
标签不起作用。
Products Template: This is the products catalog, that has another navigation bar with the category names, it should behave similar to the nav in the base template: loading the AJAX content in a div called AjaxCatalog
, but i can't make a AJAX request in this template because the script
tags won't work.
我正在使用Flask这样做。
I'm doing this with Flask.
谢谢!
推荐答案
你还没有证明你是怎样的加载HTML - 实际上你根本没有显示任何代码
You haven't shown how you are loading the HTML - in fact you've shown no code at all
但是,如果你的AJAX将HTML作为字符串获取,你可以使用以下
However, if your AJAX is getting the HTML as a string, you can use the following
const loadHtml = (text, dest) => {
const p = new DOMParser();
const doc = p.parseFromString(text, 'text/html');
const frag = document.createDocumentFragment();
while (doc.body.firstChild) {
frag.appendChild(doc.body.firstChild);
}
const ret = Promise.all([].map.call(frag.querySelectorAll('script'), script =>
new Promise(res => {
const scriptParent = script.parentNode || frag;
const newScript = document.createElement('script');
if (script.src) {
newScript.addEventListener('load', e => {
res({src:script.src, loaded: true});
});
newScript.addEventListener('error', e => {
res({src:script.src, loaded:false});
});
newScript.src = script.src;
} else {
newScript.textContent = script.textContent;
res({src:false, loaded:true});
}
scriptParent.replaceChild(newScript, script);
})
));
dest = document.querySelector(dest);
if (replace) {
dest.innerHTML = '';
}
dest.appendChild(frag);
return ret;
};
用法
let yourHTMLtext = '....'; // this would be the result of your AJAX call
loadHTML(yourHTMLtext, '#ajaxContent').then(results => {
// at this point, all scripts have been loaded, if that's something you need to know
});
这篇关于如何在AJAX请求上加载脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!