Transmitting JSON from PHP to Flex
Learn how to create JSON(JavaScript Object Notation) with PHP and display in Flex application.
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" viewSourceURL="srcview/index.html"> <fx:Script> <![CDATA[ import com.adobe.serialization.json.JSON; import mx.rpc.events.ResultEvent; import mx.rpc.http.HTTPService; private function getCd():void { var httpService:HTTPService = new HTTPService(); httpService.url = 'assets/cd.php?getCd'; httpService.useProxy = false; httpService.method = URLRequestMethod.POST; httpService.resultFormat = HTTPService.RESULT_FORMAT_TEXT; httpService.addEventListener(ResultEvent.RESULT, jsonResultHandler); httpService.send(); } private function jsonResultHandler(event:ResultEvent):void { var rawData:String = String(event.result); var cd:Object = JSON.decode(rawData); titleInput.text = cd.title; artistInput.text = cd.artist; countryInput.text = cd.country; companyInput.text = cd.company; priceInput.text = cd.price; yearInput.text = cd.year; } ]]> </fx:Script> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <mx:Form x="19" y="22"> <mx:FormItem label="title"> <s:TextInput id="titleInput"/> </mx:FormItem> <mx:FormItem label="artist"> <s:TextInput id="artistInput"/> </mx:FormItem> <mx:FormItem label="country"> <s:TextInput id="countryInput"/> </mx:FormItem> <mx:FormItem label="company"> <s:TextInput id="companyInput"/> </mx:FormItem> <mx:FormItem label="price"> <s:TextInput id="priceInput"/> </mx:FormItem> <mx:FormItem label="year"> <s:TextInput id="yearInput"/> </mx:FormItem> </mx:Form> <s:Button x="19" y="224" label="Get JSON Object" click="getCd()"/> </s:Application>
PHP script:
<?php
class Cd
{
public $title;
public $artist;
public $country;
public $company;
public $price;
public $year;
}
if(isset($_GET['getCd']))
{
$cd = new Cd();
$cd->title = 'Big Willie style';
$cd->artist = 'Will Smith';
$cd->country = 'USA';
$cd->company = 'Columbia';
$cd->price = '$9.90';
$cd->year = '1997';
echo json_encode($cd);
}
?>
Srinivas Annam
October 25, 2009 at 1:07 pm
Nice article.
One more interesting way to connect to PHP or HTTPService or any other service is to use Data Centric Development features in Flash Builder 4.
You can automatically generate forms and bind your data to UI controls versy easily with these features.
You can discover more about these features at http://sujitreddyg.wordpress.com/flash-builder-4