ColdFusion读取字符串报错:ReferenceError未定义标识符
问题解决方法
错误根源
你用eval()处理数据库读取的字符串时,JavaScript会把Rx222y208...这类内容当成变量名去查找,而非作为字符串解析,因此触发ReferenceError。
直接修复方案
移除eval,直接将数据库返回的字符串作为JavaScript字符串使用,同时用ColdFusion的encodeForJavaScript函数做转义,避免XSS风险和语法错误:
<cfquery name="getField" datasource="exmind" result="result"> select resources_gathered, completed_fields from dbo.sf where subject_id = <cfqueryparam value="#subject_id#" cfsqltype="cf_sql_integer"> </cfquery> <cfset record = getField>
// 直接输出转义后的字符串,包裹成JS字符串 resourcesGathered = "<cfoutput>#encodeForJavaScript(record.resources_gathered)#</cfoutput>"; alert(resourcesGathered); // 如果需要转成JSON字符串用于传输,直接调用JSON.stringify即可 let resourcesGatheredJSON = JSON.stringify(resourcesGathered); alert(resourcesGatheredJSON);
额外优化建议
- 查询参数化:原查询中
subject_id=#subject_id#存在SQL注入风险,已在上面代码中修正为<cfqueryparam>写法。 - 存储格式优化:如果后续需要频繁解析该字符串,建议生成时直接转成JSON格式存储,示例如下:
读取时可直接解析为JS对象使用:// 生成标准资源数组而非自定义字符串 let resourcesData = []; for (let i=0; i<resources.length; i++) { if (resources[i].visibility == true){ resourcesData.push({ x: resources[i].x, y: resources[i].y }); } } // 转成JSON字符串存入表单 document.getElementById("resources_gathered").value = JSON.stringify(resourcesData);let resourcesGathered = JSON.parse("<cfoutput>#encodeForJavaScript(record.resources_gathered)#</cfoutput>"); // 遍历资源示例 resourcesGathered.forEach(item => { console.log(`x: ${item.x}, y: ${item.y}`); });
内容的提问来源于stack exchange,提问作者Bayley Sapara
相关产品推荐
相关产品推荐

