Simple ActionScripts 3 read JSON from PHP

I am trying to read JSON data from localhost PHP in ActionsScripts3, I found code for this, but this code does not work.

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 has 3 functions, if possible, I like to use only 1 function.

+4
source share
1 answer

You cannot do this in one function just because it is an asynchronous operation. You make a request and then wait for a response. The AS3 code is erroneous and makes no 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 );
    }
+2
source

Source: https://habr.com/ru/post/1667858/


All Articles