我正在CFScript中編寫以下函數,我想確定請求的ReturnFormat,並以適當的格式返回數據。請注意,我還沒有在函數中定義ReturnFormat - 我依靠在我的調用中設置它。如何確定CFC函數內的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。然後,我可以編寫自己的返回子例程,以我想要的格式(小寫字母任何人! - 我知道如何執行BTW,這不是此問題的一部分)以XML格式返回JSON數據。