【问题标题】:AngularJS and ColdFusion CFCsAngularJS 和 ColdFusion CFC
【发布时间】:2013-02-25 18:19:39
【问题描述】:

我正在尝试使用带有 ColdFusion 后端的 AngularJS,但遇到了一些障碍。我正在使用 CF Art Gallery 数据库修改他们的“待办事项”应用程序http://angularjs.org/。我正在尝试使用 AJAX 将 ColdFusion CFC 链接到 Angular 应用程序。

下面是我的 Artists.cfc:

<cfcomponent>

<cffunction name="getArtists" access="remote" >
    <cfargument name="firstName" default="">
    <cfargument name="lastName" default="">

    <cfquery name="getArtists_sql" datasource="cfartgallery">
        SELECT
            firstname as text,
            lastname as done 
        FROM artists
        WHERE 0=0
    <cfif firstName neq "">
        AND ucase(firstname) like ucase('%#FIRSTNAME#%')
    </cfif>
    <cfif lastName neq "">
        OR ucase(lastname) like ucase('%#LASTNAME#%')       
    </cfif>
    </cfquery>

    <cfreturn getArtists_sql>
</cffunction>

</cfcomponent>

我使用 AngularJS 调用 CFC,代码如下:

function TodoCtrl($scope, $http) {
    $http.get('cfc/artists.cfc?method=getArtists&returnformat=json').
        success(function (response) {
            $scope.todos = data.DATA;
    }).
        error(function (data) {
            $scope.todos = data;
        });
}

我知道我收到了回复。下面是 Chrome 的开发者工具为我返回的 JSON 字符串:

{
"COLUMNS":
    ["TEXT","DONE"],
"DATA":[
    ["Aiden","Donolan"],
    ["Austin","Weber"],
    ["Elicia","Kim"],
    ["Jeff","Baclawski"],
    ["Lori","Johnson"],
    ["Maxwell","Wilson"],
    ["Paul","Trani"],
    ["Raquel","Young"],
    ["Viata","Trenton"],
    ["Diane","Demo"],
    ["Anthony","Kunovic"],
    ["Ellery","Buntel"],
    ["Emma","Buntel"],
    ["Taylor Webb","Frazier"],
    ["Mike","Nimer"]
]}

这看起来不像他们演示中使用的符号 Angular:

[
{text:'learn angular', done:true},
{text:'build an angular app', done:false}
]

有人可以为我指出正确的方向,让我如何让它正常工作?理想情况下,我希望保持 CFC 完整,以便可以将其重用于不同的应用程序,因此 JSON 操作必须在 Javascript 端完成。

【问题讨论】:

  • 您的问题到底是什么?顺便说一句,您的成功回调没有正确引用响应数据。应该是function (response) { $scope.todos = response.data.DATA; }。
  • 明确指出,我的问题是“如何将来自 AngularJS 的 TODO 教程的信息替换为来自 artist.cfc 的信息?我已经尝试了 function(response) {$scope.todos = response.data.DATA;} 并得到了 TypeError: Cannot read property 'DATA' of undefined
  • 我的错,我把显式的promise.success 方法(它用数据和状态参数提供回调)与promise.then 方法弄错了,它用响应对象提供回调,它有一个数据属性。但在这种情况下,您的回调应该是function(data) {$scope.todos = data.DATA;},因为您的实际 ajax 响应正文确实返回了您在答案中发布的 JSON。

标签: coldfusion angularjs cfc


【解决方案1】:

默认情况下,Coldfusion 使用不同于您习惯的 JSON 表示法。列名存储在一个数组中,而数据存储在另一个数组中。我们实施的解决方案涉及将 CFquery 更改为数组。然后 JSONEncoding 该数组。

您将在这里需要此功能:

<cffunction name="QueryToArray" access="public" returntype="array" output="false"hint="This turns a query into an array of structures.">
    <cfargument name="Data" type="query" required="yes" />

    <cfscript>
        // Define the local scope.
        var LOCAL = StructNew();

        // Get the column names as an array.
        LOCAL.Columns = ListToArray( ARGUMENTS.Data.ColumnList );

        // Create an array that will hold the query equivalent.
        LOCAL.QueryArray = ArrayNew( 1 );

        // Loop over the query.
        for (LOCAL.RowIndex = 1 ; LOCAL.RowIndex LTE ARGUMENTS.Data.RecordCount ; LOCAL.RowIndex = (LOCAL.RowIndex + 1)){

        // Create a row structure.
        LOCAL.Row = StructNew();

        // Loop over the columns in this row.
        for (LOCAL.ColumnIndex = 1 ; LOCAL.ColumnIndex LTE ArrayLen( LOCAL.Columns ) ; LOCAL.ColumnIndex = (LOCAL.ColumnIndex + 1)){

        // Get a reference to the query column.
        LOCAL.ColumnName = LOCAL.Columns[ LOCAL.ColumnIndex ];

        // Store the query cell value into the struct by key.
        LOCAL.Row[ LOCAL.ColumnName ] = ARGUMENTS.Data[ LOCAL.ColumnName ][ LOCAL.RowIndex ];

        }

        // Add the structure to the query array.
        ArrayAppend( LOCAL.QueryArray, LOCAL.Row );

        }

        // Return the array equivalent.
        return( LOCAL.QueryArray );

    </cfscript>
</cffunction>

然后您的回报将如下所示:

 <cfreturn SerializeJson(QueryToArray(getArtists_SQL),true)>

要记住的是,CFquery 对象包含其他属性,如记录计数......而且很可能,JS 只想要数据。我不知道是否有更优雅的解决方案,但这是我们在 JQgrid 遇到类似问题时所采用的解决方案。

【讨论】:

  • 嗯,将 JSON 响应从 CFC 更改为 {"ROWCOUNT":15,"COLUMNS":["TEXT","DONE"],"DATA":{"TEXT":["Aiden","Austin","Elicia","Jeff","Lori","Maxwell","Paul","Raquel","Viata","Diane","Anthony","Ellery","Emma","Taylor Webb","Mike"],"DONE":["Donolan","Weber","Kim","Baclawski","Johnson","Wilson","Trani","Young","Trenton","Demo","Kunovic","Buntel","Buntel","Frazier","Nimer"]}},但仍然不像教程中的数据那样。
  • @Chester 你说的太对了。我很抱歉。我会更新我的答案。
  • 想了想,我也得出了同样的结论,只是方式不同。我真的很想保持 CFC 清除任何 JSON 修改,以便可以重用 CFC,但我认为将来修改/添加任何 CFC 比做 javascript 更容易。话虽如此,我使用了github.com/iknowkungfoo/ArrayCollection 并将整个查询包装成它应该是的。谢谢你的帮助。现在我必须弄清楚如何让响应重新显示在我的视图中。
  • @Chester 没有什么能阻止您向 CFC &lt;cfargument name="returnType" default=""&gt; 添加第三个参数并检查它是否为“json”,然后使用上面的代码将好的 JSON 返回到您的 Angular 应用程序。
【解决方案2】:

同意布莱斯的上述回答。 我使用的 queryToArray 查看查询对象的 columnList。 这样就保留了列别名的情况。否则它将在您的 JSON 中全部大写

/**queryToArray
*  utility method to keep the code dry.
*  @hint does exactly what the name says, take a query, makes it an array of stucts
*  @hint columnLabels pass in a list of columnLabels to just return those columns
*/
public array function queryToArray(required query data, any columnLabels=false){
    var columns = listToArray(arguments.data.columnList);
    if(arguments.columnLabels != false){
            columns = listToArray(arguments.columnLabels);
    }

    var queryArray = arrayNew(1);

    for(i=1; i <= arguments.data.RecordCount; i++){

            row = StructNew();
            for (j=1; j <= ArrayLen(columns); j++){
                columnName = columns[j];
        row[columnName] = arguments.data[columnName][i];
            }
            arrayAppend(queryArray, row);
    }
    return(queryArray);
}

【讨论】:

    【解决方案3】:

    或者您可以在 javascript 中使用此辅助函数将查询作为(通用)键值对象数组。

    function CFQueryParser(data) { let items = []; Object.keys(data.DATA).forEach((i) => { let item = {}; Object.keys(data.COLUMNS).forEach((j) => { item[data.COLUMNS[j]] = data.DATA[i][j]; }); items.push(item); }) return items; }

    【讨论】:

      猜你喜欢
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多