How to use jsonutil with coldfusion7 and jquery ajax?

﹥>﹥吖頭↗ 提交于 2019-11-29 17:12:39

(Brief side note, my advice is get the cfc working separately first. It is much easier to debug CF problems that way. Do not add jquery to the mix until you have confirmed the cfc returns the desired JSON string. But back to your question ...)

The utility is easy to use. Inside your function, create an instance of it. Then pass your query object into serializeJSON(). Finally return the resulting string.

Note, your function signature must support remote access and return a string (not a query)

    <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>

You can test the cfc directly in your browser (or with cfinvoke):

    http://localhost/path/to/client.cfc?method=getClientsByName&name=foo

However, the native representation of queries is a bit awkward IMO. As Lance mentioned, you may prefer to return an array of structures instead, which is a more standard.

     <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)>
Lance

Take a look at https://stackoverflow.com/a/6257891/886591 you can use $getJSON

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

There is also a very helpful article by Ben Nadel about converting querys to arrays. Since working with queries can be a pain in json it's easier to convert them to an array first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!