提交Cardknox API表单时出现showNotification未定义错误求助
问题排查:Uncaught ReferenceError: showNotification is not defined
1. 检查toastify.js中showNotification函数的定义
确保toastify.js里正确声明并暴露了该函数:
// toastify.js 示例正确写法 function showNotification(message, type) { Toastify({ text: message, duration: 3000, close: true, gravity: "top", position: "right", style: { background: type === 'success' ? '#2ecc71' : '#e74c3c', } }).showToast(); } // 若函数被包裹在局部作用域内,需挂载到全局window对象 window.showNotification = showNotification;
- 排查函数名拼写错误(如大小写、漏写字符);
- 避免将函数封装在未暴露的局部作用域中(如自执行函数内部)。
2. 确认脚本加载顺序
在template.ejs中,必须保证toastify.js在调用showNotification的提交逻辑脚本之前加载:
<!-- 正确加载顺序 --> <script src="/js/toastify.js"></script> <script> document.getElementById('payment-form').addEventListener('submit', async (e) => { e.preventDefault(); // 提交请求到服务器 const res = await fetch('/process-transaction', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({/* 表单数据 */}) }); const result = await res.json(); // 调用通知函数 showNotification(result.msg, result.success ? 'success' : 'error'); }); </script>
- 若加载顺序颠倒,提交逻辑执行时
showNotification尚未被定义,会直接触发报错。
3. 排查EJS模板的事件绑定时机
- 如果用内联
onclick="showNotification(...)"绑定提交按钮,需确保toastify.js在页面渲染完成前已加载; - 建议将提交逻辑放在
DOMContentLoaded事件中,避免DOM未就绪时绑定事件:
document.addEventListener('DOMContentLoaded', () => { const form = document.getElementById('payment-form'); form.addEventListener('submit', async (e) => { // 提交逻辑 }); });
4. 验证server.js的响应逻辑
确保后端正确返回JSON格式的交易结果,前端能正常解析并触发通知:
// server.js 示例处理逻辑 app.post('/process-transaction', async (req, res) => { try { const cardknoxRes = await cardknoxClient.submitTransaction(req.body); if (cardknoxRes.Approved === 'Y') { res.json({ success: true, msg: '交易成功' }); } else { res.json({ success: false, msg: `交易失败:${cardknoxRes.Error}` }); } } catch (err) { res.json({ success: false, msg: `服务器错误:${err.message}` }); } });
5. 检查脚本加载状态
在浏览器网络标签页查看toastify.js的加载状态:
- 若返回404,说明文件路径配置错误,需修正
template.ejs中的脚本引用路径; - 若存在其他加载报错,需优先解决脚本本身的加载问题。
内容的提问来源于stack exchange,提问作者jospeh monn
相关产品推荐
相关产品推荐

