Domanda

I have an AJAX call to a remote CFC and get the data back with JSON just how I like, but I'm having trouble outputting the data without having to guess the structure index with hardcoded index values such as: $('#result').val( obj.DATA[0][3] );

If I hardcode the index such as [3] if I change the query in the CFC I have to change the AJAX result. So I want to refer to the returned data by the colmn name but can't figure it out. Here's my AJAX and the result from a remote CFC:

$.ajax({
            url: '/app/components/MailingsReport.cfc',
            //POST method is used
            type: "POST",
            //pass the data 
            data: {
                method: "getCreativeByID",
                creativeID: $('#hdnCreativeID').val(),
                datasource: "shopping_cart",
        queryformat: "column"
                 },
            success: function(response){
                var obj = $.trim(response);
        var obj = jQuery.parseJSON(obj);
                //alert("response");
                $('#txtSubject').val( obj.COLUMNS["SUBJECT"][0] );
                }
            }

        });

CFC:

<!---gets the data for the creative--->
    <cffunction name="getCreativeByID" returntype="any" returnformat="JSON" access="remote" output="No">
        <cfargument name="creativeID" required="Yes" type="numeric" />
        <cfargument name="datasource" required="Yes" type="string" />

        <!--- Select creatives and {clickurl} --->
        <cfquery name="qGetCreativeData" datasource="#arguments.datasource#">
            exec sp_get_email_creative @creativeid = #arguments.creativeID#
        </cfquery>

        <cfreturn qGetCreativeData />

    </cffunction>

Result:

This is the result from the CFC

Any help would be appreciated! Thanks.

È stato utile?

Soluzione

This works in everything except IE8 and below. if you need full compatibility you could write your own indexOf JS method.

$('#result').val( obj.DATA[0][ obj.COLUMNS.indexOf('Creativename') ] );

If you need it, this page has the instructions on adding the indexOf to your array prototypes in browsers that don't support it directly: http://www.tutorialspoint.com/javascript/array_indexof.htm

Altri suggerimenti

You can also return queries in JSON with the column names as keys in a each row of data using SerializeJSON(data, true). So in your cfc, remove the returnformat="JSON", and replace

with

In your JavaScript code you should now be able to loop over the data part of the returned JSON string row-by-row, and reference the values by the column names.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top