Reputation: 247
I'm trying to read JSON data from localhost PHP in ActionsScripts3, I found some code to do it but this code doesn't works.
PHP:
<?php
$arr = array ('DATA1'=>"111",'DATA2'=>"222");
header('Content-Type: application/json');
echo json_encode($arr);
?>
AS3:
import flash.events.*;
import flash.net.*;
var urlLoader:URLLoader=new URLLoader();
function ReadJsonPhp () :void
{
addEventListener(Event.COMPLETE,init);
}
function init(event:Event)
{
urlLoader.load(new URLRequest("http://localhost/asphp.php"));
urlLoader.addEventListener(Event.COMPLETE, urlLoaderCompleteHandler);
}
function urlLoaderCompleteHandler(e:Event):void
{
trace(e.target.data) ;
var arrayReceived:Object = JSON.parse(e.target.data);
}
ReadJsonPhp();
This code have 3 function if possible i like to use only 1 function.
Upvotes: 4
Views: 80
Reputation: 865
You can't do it in one function just because it's an async operation. You make a request and then wait for some response. The AS3 code just wrong and doesn't make any sense. Here is a simple example:
private var loader:URLLoader;
private var request:URLRequest;
private function load():void
{
request = new URLRequest("http://localhost/asphp.php");
loader = new URLLoader()
loader.addEventListener(Event.COMPLETE, onComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.load(request);
}
private function onError(e:Event):void
{
// handle error
}
private function onComplete(e:Event)
{
trace(e.target.data);
// keep in mind that if the Json string is invalid here will be SyntaxError exception!
var json:Object = JSON.parse( e.target.data );
trace( "json.DATA1 = ", json.DATA1 );
trace( "json.DATA2 = ", json.DATA2 );
}
Upvotes: 2