You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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);

额外优化建议

  1. 查询参数化:原查询中subject_id=#subject_id#存在SQL注入风险,已在上面代码中修正为<cfqueryparam>写法。
  2. 存储格式优化:如果后续需要频繁解析该字符串,建议生成时直接转成JSON格式存储,示例如下:
    // 生成标准资源数组而非自定义字符串
    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);
    
    读取时可直接解析为JS对象使用:
    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:42:22