【发布时间】:2015-09-18 08:53:27
【问题描述】:
我正在尝试将 JQUERY 与 Coldfusion 一起使用。我想从 cfc 文件中的函数以 JSON 格式从数据库中检索结果。我需要使用几个查询手动创建 json:
<cfcomponent output="false">
<cffunction name="getTransports" access="remote" returnformat="JSON" output="false">
<cfargument name="CITY_TO" type="string" required="yes">
<cfargument name="CITY_FROM" type="string" required="yes">
<cfquery name ="transport" datasource="#application.datasource#">
<!---Query Transports--->
select * from TRANSPORTS
</cfquery>
<cfset transports = arrayNew(1)>
<cfloop from="1" to="#transport.recordcount#" index="i">
<cfquery name="defined_transport" datasource="#application.datasource#">
select * from TABLE_FRAIS
where CITY_TO = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.CITY_TO#">
and CITY_FROM = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.CITY_FROM#">
and CTRP_ST_CODE = '#transport.TRANSPORT_CODE#'
</cfquery>
<cfif defined_transport.recordCount eq 0>
<cfset transport_value = "#transport.TRANSPORT_NAME# (not defined)">
<cfelse>
<cfset transport_value = "#transport.TRANSPORT_NAME#">
</cfif>
<cfset transpVO = structNew() />
<cfset transpVO['ID']= #transport.TRANSPORT_CODE# />
<cfset transpVO['VALUE']= #transport_value# />
<cfset transports[i] = transpVO />
</cfloop>
<cfreturn transports>
</cffunction>
</cfcomponent>
当我在 JQUERY 脚本中检索结果时,我得到一个字符串 JSON:
[ { "ID" : "APEX",
"VALUE" : "Apex (not defined)"
},
{ "ID" : "AVI",
"VALUE" : "Plane (not defined)"
},
{ "ID" : "TRAIN 1",
"VALUE" : "Train 1st class"
},
{ "ID" : "VOIT",
"VALUE" : "Car"
},
{ "ID" : "ZERO",
"VALUE" : "Cost 0 (not defined)"
}
]
编辑:
这里是我的 JQUERY 脚本,用于通过 Coldfusion 检索数据:
$().ready(function() {
$.ajax({
type: 'GET',
url: 'transports.cfc',
data: {
method: 'getTransports',
CITY_TO: 'LUX',
CITY_FROM: 'UWP'
},
dataType: "application/json", //this is important responsetype:'JSON',
success: function(result) {
var select = $("##transp");
select.empty();
select.append(
new Option('Select transport', '-1')
);
console.log(result); // display the JSON
console.log(result.length); // displays 252
},
error: function(xhr, message) {
alert('ajax request failed');
console.log(xhr, message);
}
});
});
结果显示在控制台中,如果我不知道如何填充下拉列表。我试着补充一下:
select.append(
new Option(item.ID, item.VALUE)
);
我在没有文本的下拉列表中获得 252 行。
但我正在尝试使用它来填充下拉列表,但我做不到。
你能告诉我我的coldfusion函数和我的JSON结果是否正常吗?
问候,
【问题讨论】:
-
您的 JSON 结果似乎没问题(在jsonlint.com 中有效)。当您尝试填充下拉列表时不会出现问题吗?你没有解释为什么你不能这样做。
-
我在帖子中添加了JQUERY代码。
标签: jquery json ajax coldfusion-10