Search code examples
phpactionscript-3jsonurlloader

Load JSON data with URL loader


I am new to action script 3.0. Help me to understand how can I load data with URLLoader.

So, I have an aplication like:

var PATH:String = "http://www.somesite.com/myFirstPage.php?a=10&b=20";


var urlRequest:URLRequest = new URLRequest(PATH);
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
urlLoader.load(urlRequest);

function urlLoader_complete(evt:Event):void {
    some_result = urlLoader.data;
}

php script looks like:

<?php
//retrieve GET params

int c = a + b; //a and b come from GET request

return "{{"result_equal":"20"}}"; //result in JSON

?>

I don't really understand how JSON result from .php page gets in my URLLoader object. Help me by simple example, please. Thanx!


Solution

  • You need a few things here. First off, you'll need a JSON library, because somehow it isn't built into Flash, even with their modified E4X core:

    https://github.com/mikechambers/as3corelib

    This should give you the following bits of code:

    import com.adobe.serialization.json.JSON;
    
    function urlLoader_complete(e:Event):void 
    {
       var loader:URLLoader = URLLoader(e.target);
       var some_result:Object = JSON.decode(loader.data);
    }
    

    Now... your PHP code is a mess. The best way to create JSON is to just use the json_encode function:

    $retVal = array('result_equal'=>20);
    echo json_encode($retVal);