如何确定CFC函数内的ReturnFormat并以所选格式返回数据?

时间:2011-12-28 21:08:48

标签: coldfusion coldfusion-9 cfc wddx

我在CFScript中编写以下函数,我想确定所请求的ReturnFormat,并以适当的格式返回数据。请注意,我还没有在函数中定义ReturnFormat - 我依赖于在我的调用中设置它。

例如,调用此函数的URL类似于: http://localhost/com/Calendar.cfc?method=getCalendars&UserName=demo&returnFormat=json

/**
* 
* @hint Returns All Calendar records for one user.
* @output false
*/
remote any function GetCalendars(required string Username) {
    var data = [];
    var success = false;
    var message = "";

    try {
        query = new Query(); 
        query.setDataSource(APPLICATION.DSN);
        query.addParam(name = "username", value = Username, cfsqltype = "varchar");
        query.setSQL("
            SELECT idn, CalendarName, CalendarURL, CalendarColor
            FROM Calendars
            WHERE Username = :username 
            ORDER BY CalendarName, idn
        ");
        result = query.Execute();
        rs = result.getResult();
        success = true;
        message = "Success";
        records = rs.RecordCount;
    }
    catch (any excpt) {
        success = false;
        message = "An error occurred while getting calendars for user: " & Username;
    }
    finally {
        //TODO: If ReturnFormat = json, return a JSON string
        //TODO: If ReturnFormat = wddx, returna WDDX object
        //TODO: If ReturnFormat = plain, return an XML string
        return rs;
    }
} //end GetCalendars



现在,这个方法将返回一个ColdFusion自动格式化的JSON字符串,如下所示:

  

{"COLUMNS":["IDN","CALENDARNAME","CALENDARURL","CALENDARCOLOR"],"DATA":[[1,"Demo Calendar 1","http:\/\/localhost\/calendar\/feeds\/demo1\/basic","#43cd80"],[2,"Demo Calendar 2","http:\/\/localhost\/calendar\/feeds\/demo2\/basic","#9a9cff"]]}

或者像这样的WDDX对象:

  

<wddxPacket version='1.0'><header/><data><recordset rowCount='2' fieldNames='IDN,CALENDARNAME,CALENDARURL,CALENDARCOLOR' type='coldfusion.sql.QueryTable'><field name='IDN'><number>1.0</number><number>2.0</number></field><field name='CALENDARNAME'><string>Demo Calendar 1</string><string>Demo Calendar 2</string></field><field name='CALENDARURL'><string>http:\/\/localhost\/calendar\/feeds\/demo1\/basic</string><string>http:\/\/localhost\/calendar\/feeds\/demo2\/basic</string></field><field name='CALENDARCOLOR'><string>#43cd80</string><string>#9a9cff</string></field></recordset></data></wddxPacket>

但是当我设置returnFormat=plain时,它以“无效的返回类型”错误失败。

基本上我需要有一种方法来测试ReturnFormat。然后我可以编写自己的返回子程序来返回按照我想要的方式格式化JSON数据(小写名称任何人! - 我知道如何做BTW,这不是这个问题的一部分)和XML格式。

1 个答案:

答案 0 :(得分:2)

您没有使用returnFormat检测或执行任何操作。这不是重点。 returnFormat告诉CF它应该如何包装你的结果。重复:你不担心这个。周期。

所以给一个生成数组的CFC方法,你只需要返回数组。 CF,如果看到returnformat = json,将处理将其转换为JSON。

如果看到returnformat = plain,则会抛出错误(因为数组不能是普通字符串)。

这有意义吗?

哦 - 所以我看到你的最后一段。如果你想尝试自己的回报,你不应该依赖returnformat。这已经融入了CF.我建立我的api只是总是返回JSON,句点,并做自己的格式。如果在方法上设置returnFOrmat = plain,它会告诉CF不做任何事情。只要你返回一个字符串,那么你就可以了。

相关问题