AJAX加载Footer内联脚本引发页面异常问题求助
我构建了header.html与footer.html文件,通过AJAX将其追加至HTML页面,实现代码如下:
$(function(){ $.ajax({ type: "GET", url: "header.html", dataType: "html", success: function(header) { $("body #header").append(header); }, error: function(){ alert("failed call header"); } }); return false; }); $(function(){ $.ajax({ type: "GET", url: "footer.html", dataType: "html", success: function(footer) { $("body #footer").append(footer); }, error: function(){ alert("failed call footer"); } }); return false; });
Header可正常追加,但Footer因包含内联脚本document.write(new Date().getFullYear());出现异常:页面加载后所有元素消失,仅显示“2023”,样式也失效;移除该脚本后页面显示正常,但Footer中的年份无法显示;添加$(document).ready包裹该脚本后仍无效果,恳请协助解决此问题。
解决方案
核心原因
页面加载完成后调用document.write会清空当前页面所有内容——因为此时文档流已关闭,document.write会自动触发document.open(),这会直接覆盖原有DOM结构和样式,最终只剩写入的年份文本。
可行解决办法
方案1:预留容器,在AJAX回调中插入年份
- 修改
footer.html,添加年份展示容器:<!-- footer.html 示例内容 --> <footer> <p>© <span class="copyright-year"></span> 某某公司</p> </footer> - 更新AJAX回调代码,动态插入年份:
$(function(){ $.ajax({ type: "GET", url: "footer.html", dataType: "html", success: function(footer) { var $footerDom = $(footer); // 给预留容器设置年份 $footerDom.find('.copyright-year').text(new Date().getFullYear()); $("body #footer").append($footerDom); }, error: function(){ alert("failed call footer"); } }); return false; });
方案2:直接替换HTML内容中的document.write代码
如果无法修改footer.html,可在获取到HTML内容后,替换掉危险的document.write语句:
$(function(){ $.ajax({ type: "GET", url: "footer.html", dataType: "html", success: function(footer) { // 替换document.write为当前年份文本 var processedFooter = footer.replace( /document\.write\(new Date\(\)\.getFullYear\(\)\);/g, new Date().getFullYear() ); $("body #footer").append(processedFooter); }, error: function(){ alert("failed call footer"); } }); return false; });
方案3:提取脚本逻辑在DOM插入后执行(不推荐)
如果footer中的脚本逻辑复杂,可提取后在DOM插入完成后执行,但这种方式存在安全风险,仅在必要时使用:
$(function(){ $.ajax({ type: "GET", url: "footer.html", dataType: "html", success: function(footer) { $("body #footer").append(footer); // 手动执行年份逻辑,需确保footer中有对应元素 document.getElementById('year').textContent = new Date().getFullYear(); }, error: function(){ alert("failed call footer"); } }); return false; });
内容的提问来源于stack exchange,提问作者abcid d
相关产品推荐
相关产品推荐

