Passing and returning a ColdFusion structure through jQuery

I have a ColdFusion session variable that is a data structure. My goal is to make a jQuery call that does one of two things through Ajax:

  • sends this ColdFusion structure to the component of the ColdFusion component, updates the element of this structure with a new line and returns the same structure back.

or

  • executes a component of the ColdFusion component that creates a new line, returns this line, and assigns this new line to an element of the same ColdFusion session structure after an Ajax call.

I would have thought it would be easy, but I was having problems. Does anyone know what I need to do?

+6
source share
1 answer

Well, the session structure of CF and jQuery work in two different areas: CF on the server and jQuery in the browser. To "send this ColdFusion structure to [cfc] ..." from Ajax, you will have to serialize the session structure as a json string and then pass that json string to the client. Most likely, you will want to do this as part of the page rendering 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, for example:

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

Note that you must enable json2.js for serialization, as some coughIEcough browsers do not support JSON.stringify() natively.

Update

I updated the jquery sample code to show how you can update the javascript object to use a response from CFC. To work correctly, 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> 
+10
source

Source: https://habr.com/ru/post/909858/


All Articles