JavaScript无法添加列表新项及CSP问题技术求助
Node.js + EJS 表单动态添加功能异常及CSP问题
我用Node.js结合EJS模板开发了Web表单,以Excel文件作为数据库,每个Sheet对应一个分类。用户未找到所需选项时可输入内容,系统会生成对应分类的22位编码,但负责动态添加项的JavaScript功能异常:系统无法定位输入元素,导致编码无法保存至Excel并更新表单。
已排查内容
- 验证过元素ID与Sheet名称的一致性
- 排查了HTML渲染与脚本执行的顺序
- 添加
console.log追踪数据流,但仍未找到根因 - 尝试多种方案解决Content Security Policy(CSP)问题,均未生效
出错的EJS脚本代码
function addNew(sheetName) { console.log('addNew called with sheetName:', sheetName); const newInput = document.getElementById(`new${sheetName}`); console.log('newInput element:', newInput); if (!newInput) { console.log(`Input element for ${sheetName} not found.`); return; } const inputValue = newInput.value; console.log('Input value:', inputValue); if (!inputValue.trim()) { console.log('Input is empty. Not adding to the sheet.'); return; } // Send the data to the server using Axios AJAX request axios.post('/add', { sheetName, newInput }) .then(response => { console.log('Data added successfully:', response.data); // Update the current page with the newly added data const newRow = `<tr><td>${newInput}</td><td>${response.data.code}</td></tr>`; const tableBody = document.getElementById(`${sheetName.toLowerCase()}TableBody`); tableBody.insertAdjacentHTML('beforeend', newRow); // Clear the input field after adding document.getElementById(`new${sheetName}`).value = ''; }) .catch(error => { console.error('Error adding data:', error); }); }
报错截图

内容的提问来源于stack exchange,提问作者lea__
相关产品推荐
相关产品推荐

