我试图了解如何使用 JSONutil 在 jquery 和 Coldfusion 之间序列化/反序列化 JSON。我无法使用 Coldfusion 7,因此无法在 cfc 中使用 returnformat='json'
属性。
客户端.cfc:
<cfcomponent>
<cffunction name="GetClientsByName"
returntype="query"
hint="get clients from search term">
<cfargument name="name" type="string" required="yes">
<cfquery name="GetClientsByName" datasource="#application.dsn#">
SELECT client_id, client_name
FROM Clients
WHERE client_name LIKE '%' + <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.name#"> + '%'
</cfquery>
<cfreturn GetClientsByName>
</cffunction>
</cfcomponent>
jquery ajax 调用:
function getClients(name){
$.ajax {
type: "post"
url: "/surveymanagement/admin/client.cfc",
dataType: "json",
data: {
method: "GetClientsByName",
name: name
},
success: function(data){
$("#here").html(data)
}
}
现在我在哪里以及如何使用 jsonutil 来让它工作?
jsonutil 的站点: http://jsonutil.riaforge.org/
最佳答案
(简要说明,我的建议是首先让 cfc 单独工作。这样调试 CF 问题要容易得多。在确认 cfc 返回所需的 JSON 字符串之前,不要将 jquery 添加到混合中。但是返回对于你的问题...)
该实用程序易于使用。在您的函数内,创建它的一个实例。然后将您的查询对象传递给 serializeJSON()
。最后返回结果字符串。
注意,您的函数签名必须支持远程访问并返回字符串(而不是查询)
<cffunction name="GetClientsByName" access="remote" returntype="string">
<cfargument name="name" type="string" required="yes">
<!--- always localize function variables --->
<cfset var util = createObject("component", "path.to.JSONUtil")>
<cfset var getClientsByName = "">
.... run cfquery .....
<!--- return JSON string --->
<cfreturn util.serializeJSON(getClientsByName)>
</cffunction>
您可以直接在浏览器中测试 cfc(或使用 cfinvoke
):
http://localhost/path/to/client.cfc?method=getClientsByName&name=foo
但是,在我看来,查询的 native 表示有点尴尬。正如兰斯提到的,您可能更愿意返回结构数组,这是更标准的。
<cfset var results = arrayNew(1)>
<cfset var elem = "">
... run query ...
<cfloop query="getClientsByName">
<cfset elem = structNew()>
<cfset elem["client_id"] = getClientsByName.client_id>
<cfset elem["client_name"] = getClientsByName.client_name>
<cfset arrayAppend(results, elem)>
</cfloop>
<cfreturn util.serializeJSON(results)>
关于jquery - 如何将 jsonutil 与 Coldfusion7 和 jquery ajax 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15123399/