|
|
How To Return XML In ColdFusion For AJAX
By Raymond Camden
Expert Author
Article Date: 2007-02-12
I've blogged this before, but only as a side point. Since the question came in to me this morning I thought I'd mention it again in a new post.
The question is simple - how do you return XML data in ColdFusion to be consumed by AJAX? (Or really any source.)
First off - if you want to return XML from a CFC method, you have to use returnType="xml". If you do not, the result will be WDDX encoded. Consider this method:
<cffunction name="test" returnType="string" access="remote" output="false">
<cfset var xml = "">
<cfxml variable="xml">
<root>
<people>ray</people>
<people>jeanne</people>
</root>
</cfxml>
<cfreturn xml>
</cffunction>
Viewed in your browser, the result is:
<wddxPacket version='1.0'><header/><data><string><?xml version="1.0" encoding="UTF-8"?><char code='0a'/><root><char code='0a'/><char code='09'/>
<char code='09'/><people>ray</people><char code='0a'/><char code='09'/>
<char code='09'/><people>jeanne</people><char code='0a'/><char code='09'/><char code='09'/></root></string></data></wddxPacket>
(Note, I added a line break or two so it wouldn't break the site layout.)
If you switch the returnType to XML, you then get:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<people>ray</people>
<people>jeanne</people>
</root>
So far so good. Before I go on - a quick note. You have to actually return an XML string or XML object. You can't just return a query and expect the returnType="xml" to convert it for you. That would be nice probably. (If you need an easy way to create XML, check out toXML.)
What if you don't have ColdFusion 7? First - buy it and mention my name! If you must use ColdFusion 6, create a ColdFusion page called proxy.cfm. This CFM file will call your CFC and then return the XML. Here is an example taken from BlogCFC:
<cfcontent type="text/xml">
<cfoutput>#queryToXML(entries, "entries", "entry")#</cfoutput>
In this case, I used a UDF to convert a query into an XML string. I use cfcontent to let the browser know XML is being returned. As a last step, I set up my AJAX front end to hit proxy.cfm instead of the CFC.
Comments
Tag: XML, Coldfusion, AJAX
Add to Del.icio.us | Digg | Reddit | Furl
About the Author:
Raymond Camden, ray@camdenfamily.com
http://ray.camdenfamily.com
Raymond Camden is Vice President of Technology for roundpeg, Inc. A long
time ColdFusion user, Raymond has worked on numerous ColdFusion books
and is the creator of many of the most popular ColdFusion community web
sites. He is an Adobe Community Expert, user group manager, and the
proud father of three little bundles of joy.
|
|
|
|