我有一个创建包含JSON的输出字符串的cfc。有效负载没有问题,但是接收它的人告诉我数据是以text/html格式传入的,他的程序无法识别它是有效的,因为它需要是application/json。
因此,我修改了CFFUNCTION语句中的参数,并构建了一个小测试程序,该程序如下所示:
<cffunction name="Test" httpmethod="get" returntype="JSON" output="yes" access="remote">
<cfset JSON='{"Test": "A"}'>
<cfreturn JSON>
</cffunction>但是当我远程执行这个cfc时,我得到了错误消息"The value returned from the Test function is not type JSON“。
这应该很简单,但是我看不到需要做什么才能返回一个带有application/json类型的JSON字符串。
发布于 2021-03-04 20:47:47
您的第一个问题将是returntype="JSON" --看起来您混淆了returntype和returnformat。有多种方法可以实现你想要做的事情,例如,每种方法都会返回相同的结果:
<!--- Function returns a struct, ask CF to convert it to JSON using returnformat: --->
<cffunction name="Test2" returntype="struct" returnformat="JSON" output="false" access="remote">
<cfset var myStruct={"Test"="A", "foo"="bar"} />
<cfreturn myStruct />
</cffunction>
<!--- Function uses a struct, but serializes as a JSON string before returning --->
<cffunction name="Test3" returntype="string" returnformat="plain" output="false" access="remote">
<cfset var myStruct={"Test"="A", "foo"="bar"} />
<cfreturn SerializeJSON(myStruct)>
</cffunction>
<!--- Same as above but another variation of struct notation.
Note that most CF environments will convert unquoted key names to uppercase
unless you enable serialization.preserveCaseForStructKey at application or CF Admin level --->
<cffunction name="Test4" returntype="string" returnformat="plain" output="false" access="remote">
<cfset var myStruct=structNew() />
<cfset myStruct['Test'] = "A" />
<cfset myStruct['foo'] = "bar" />
<cfreturn SerializeJSON(myStruct) />
</cffunction>
<!--- Manually build the JSON string yourself from scratch, beware of encoding/escaping issues --->
<cffunction name="Test5" returntype="string" returnformat="plain" output="false" access="remote">
<cfset var myJSONString='{"Test":"A","foo":"bar"}' />
<cfreturn myJSONString />
</cffunction>请注意,仅使用上述代码并不会将内容类型响应头设置为application/json,如果您的调用者确实关心这一点,那么您需要这样的代码:<cfheader name="Content-Type" value="application/json; charset=utf-8" /> ...but您引用的The value returned from the Test function is not of type JSON错误是CF运行时错误,而不是浏览器/ajax错误。该错误的完整文本通常为:
The value returned from the Test function is not of type JSON. If the component name is specified as a return type, it is possible that either a definition file for the component cannot be found or is not accessible.
https://stackoverflow.com/questions/66465978
复制相似问题