Passing and returning ColdFusion Structure via JQuery

纵饮孤独 提交于 2020-01-01 05:14:07

问题


I have a ColdFusion session variable that's a structure of data. My goal is to execute a jQuery call that does one of two things via Ajax:

  1. sends that ColdFusion structure to a ColdFusion component method, updates an element of that structure with a newly created string, and returns that same structure back.

or

  1. executes a ColdFusion component method that creates a new string, returns that string, and assigns that new string to an element of that same ColdFusion session structure after the Ajax call.

I would think it'd be easy, but I've been having some problems. Anybody know what I would need to do?


回答1:


Well, the CF session structure and jQuery operate in two different spheres - CF on the server and jQuery in the browser. In order to "send that ColdFusion structure to a [cfc]..." from Ajax, you'll have to have serialized the session structure as a json string and then transmitted that json string to the client somehow. Most likely, you'll want to do this as part of the rendering of the page to the client:

<cfoutput>var jsonStruct = #SerializeJSON(session.myStruct)#;</cfoutput>

Then you can use the jsonStruct variable from your jQuery code as needed (as a real JS object). When you need to send it back to CF, you can serialize it again on the Javascript side, like so:

$.ajax({
   url: "foo.cfc?method=myMethod", 
   dataType: "json",
   data: {myStruct: JSON.stringify(jsonStruct)}, 
   success: function (respJSON) {
      jsonStruct = respJSON;
   }
});

Note that you should include json2.js to do the serialization, since some browsers coughIEcough don't support JSON.stringify() natively.

Update

I've updated the example jquery code to show how you can update the javascript object to use the response from the CFC. To work properly, your CF will need to look something like this:

<cffunction name="myMethod" access="remote" returnFormat="json">
  <cfargument name="myStruct" type="string">

  <cfset var realStruct = DeserializeJSON(arguments.myStruct)>

  <cfset session.myStruct = realStruct><!--- or whatever you want to do with it at this point --->

  <cfreturn session.myStruct>
</cffunction>


来源:https://stackoverflow.com/questions/9541260/passing-and-returning-coldfusion-structure-via-jquery

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