如果您有一组变量希望被视为字符串(例如邮政追踪号码“9449311899561067336896”),您可能会遇到 ColdFusion 认为字符串看起来像数字的问题。ColdFusion 可能会尝试将字符串转换为整数,但如果它们对于整数来说太长,则可能会导致错误。当字符串源自反序列化 JSON 中的数组时,可能会发生这种情况。
你可能认为你可以使用这样的字符串:
<cfset trackIdXml = "" />
<!--- Loop through all tracking numbers and build the XML --->
<cfloop array="#trackingNumsArray#" index="i">
<cfset trackIdXml &= "<TrackID ID=""" />
<cfset trackIdXml &= #trackingNumsArray[i]# />
<cfset trackIdXml &= """/>" />
</cfloop>
但这会导致错误,例如Cannot convert the value 9.449311899561067E21 to an integer because it cannot fit inside an integer.
相反,您可以使用 cfscript 和java.lang.StringBuffer
:
<cfscript>
//This variable will store the XML that is used in the API request to list each tracking number
//We must tell ColdFusion that this is a string buffer, and use .append(). Why?
//ColdFusion will try to convert the tracking number to a integer if we do not explicitly tell it
//to treat it as a string.
trackIdXml = createObject("java", "java.lang.StringBuffer").init();
for (trackingNum in trackingNumsArray) {
trackIdXml.append('<TrackID ID="');
trackIdXml.append(#trackingNum#);
trackIdXml.append('"/>');
}
</cfscript>
该trackIdXml
变量是在 cfscript 标记内创建的,但仍可以像其他 Coldfusion 变量一样使用,例如在 cfreturn<cfreturn #trackIdXml# />
这是一个完整的真实示例,需要将类似整数的字符串保存为字符串。这是一个接受 USPS 跟踪号码数组的函数,并从 USPS 的 API 返回包裹状态响应:
<cfcomponent>
<cffunction name="uspsLookup" access="remote" returntype="string" returnformat="plain" output="yes">
<cfargument name="trackingNums" type="string" required="yes" />
<cfset trackingNumsArray = DeserializeJSON(trackingNums, true) />
<cfscript>
trackIdXml = createObject("java", "java.lang.StringBuffer").init();
for (trackingNum in trackingNumsArray) {
trackIdXml.append('<TrackID ID="');
trackIdXml.append(#trackingNum#);
trackIdXml.append('"/>');
}
</cfscript>
<cfset userid = "XXXXXXXXXXXX" />
<cfhttp
method="GET"
url='http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=<TrackRequest USERID="#userid#">#trackIdXml#</TrackRequest>'>
</cfhttp>
<cfif #cfhttp.Statuscode# IS "200 OK" >
<cfreturn "#cfhttp.Filecontent#">
<cfelse>
<cfreturn "error||#cfhttp.Statuscode#">
</cfif>
</cffunction>
</cfcomponent>