Revised 8/16/2007: Added this page.
Converts a JSON-encoded string to a JavaScript variable.
ColdFusion.JSON.decode(string)
ColdFusion.JSON.encode, DeserializeJSON, SerializeJSON, "Using Ajax Data and Development Features" in the ColdFusion Developer's Guide, The JSON.org web site
ColdFusion 8: Added this function
|
Parameter |
Description |
|---|---|
| string | The string to encode. |
A Javascript variable containing the data in the JSON encoded string.
Use this function when you must explicitly convert between JavaScript and JSON format, for example, when you must call a remote function that is not in a CFC.
If the JSON string has a security prefix as defined by the Server Settings > Settings page of the ColdFusion Administrator or specified in the cfapplication or cffunction tags, the function strips the prefix before decoding the string.
The following example uses the ColdFusion.JSON.decode and ColdFusion.JSON.encode functions When the user clicks the “Call” link, the callMe function encodes the String as JSON and calls the echo CFC’s plainEcho function with the result. The function also sets the return format to plain, so that the CFC function does not automatically convert its return value to JSON, and sends plain text instead.
The echo.cfc component has two functions:
The main page has the following lines:
<cfajaxproxy cfc="echo">
<cfajaximport>
<html>
<head>
<script>
function callme()
{
var e = new echo();
e.setReturnFormat('plain');
var args = {a:"Hello again!"};
var argsJSON = ColdFusion.JSON.encode(args);
var json = e.plainEcho(argsJSON);
var o = ColdFusion.JSON.decode(json);
alert(o.A);
}
</script>
</head>
<body>
<a href="javascript:callme()">Call</a>
</body>
</html>
The echo.cfc file can be as simple as the following lines:
<cfcomponent output="false">
<cffunction name="echo" access="remote">
<cfargument name="text">
<cfset var ret = StructNew()>
<cfset ret.a = text>
<cfreturn ret>
</cffunction>
<cffunction name="plainEcho" access="remote">
<cfargument name="text">
<cfset t = deserializeJSON(text)>
<cfset ret = echo(t.A)>
<cfreturn serializeJSON(ret)>
</cffunction>
</cfcomponent>