jsoncoldfusionfw1

How do I return JSON from an action in FW/1?


FW/1 seems to be oriented to returning complete web pages what if JSON data is needed? A typical layout looks like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <title>User Manager</title>
   <link rel="stylesheet" type="text/css" href="assets/css/styles.css" />
</head>
<body>


<h1>User Manager</h1>

<ul class="nav horizontal clear">
<li><a href="index.cfm">Home</a></li>
<li><a href="index.cfm?action=user.list" title="View the list of users">Users</a></li>
<li><a href="index.cfm?action=user.form" title="Fill out form to add new user">Add User</a></li>
<li><a href="index.cfm?reload=true" title="Resets framework cache">Reload</a></li>
</ul>

<br />

<div id="primary">
    <cfoutput>#body#</cfoutput>
</div>

</div>

</body>
</html>

Solution

  • I have used code that overrides the onMissingView() method of Framework.cfc.

    I wrap my response up in a variable named rc.json then use code similar to this in my Application.cfc.

    function onMissingView( rc ){
        if( structKeyExists( rc, 'json' ){
            var response = getPageContext().getresponse()
            response.setContentType( 'application/json' );
            return serializeJSON( rc.json );
        }
        else{
            //we need this to fire off valid onMissignView error.
            raiseException( "FW1.viewNotFound", "Unable to find a view for '#request.action#' action.", " '#request.missingView#' does not exist.");
        }
    }
    

    I use other logic to do a cfdump of rc.json when request is not an AJAX request. But this is scaled down to bare minimum.