我正在 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 数据(小写名称任何人!-顺便说一句,我知道如何做,这不是这个问题的一部分)和 XML 格式。