S.Raaj Nishanth
S.Raaj Nishanth

Reputation: 242

How to post JSON data using Actionscript 3.0?

I have to work with webservices in Actionscript. I found the following code that allows me to use JSON URLs that implement only the GET method. However, it doesn't work for POST methods (doesn't even enter the "onComplete" method). I searched the net and was unable to find any answers. How can i "POST" JSON data using Actionscript 3.0?

package 
{
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.*;
import com.adobe.serialization.json.JSON; 

public class DataGrab extends Sprite {

    public function DataGrab() {

    }

    public function init(resource:String):void {
            var loader:URLLoader = new URLLoader();
            var request:URLRequest = new URLRequest(resource);
            loader.addEventListener(Event.COMPLETE, onComplete);
            loader.load(request);
    }       

    private function onComplete(e:Event):void {
            var loader:URLLoader = URLLoader(e.target);
            var jsonData:Object = JSON.decode(loader.data);
            for (var i:String in jsonData)
            {
                trace(i + ": " + jsonData[i]);
            }
    }
}
}

Upvotes: 2

Views: 8100

Answers (3)

khuzama mohammed
khuzama mohammed

Reputation: 1

stop();

function getStageReference():void { stage = this; }

enterFrame.addEventListener(function(event:Event):void {

});

class MyClass { constructor(value:number) { } }

Upvotes: 0

Javier Gutierrez
Javier Gutierrez

Reputation: 559

I'm doing it with

import com.adobe.serialization.json.JSON;

var messages:Array = new Array ();  
messages.push ({"nombreArchivo":"value"});
messages.push ({"image":"value"});  

var vars: URLVariables = new URLVariables();
vars.data   = JSON.encode(messages);

var req: URLRequest = new URLRequest();
req.method      = URLRequestMethod.POST;
req.data        = vars;
req.url         = "crearIMG.php"

var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, handleServerResponse);
loader.load(req);

Upvotes: 4

shanethehat
shanethehat

Reputation: 15570

You need to specify the method used with your URLRequest object. The default is GET. This could be a second argument to your init method:

public function init(resource:String,method:String = "GET"):void {
    var loader:URLLoader = new URLLoader();
    var request:URLRequest = new URLRequest(resource);
    request.method = method;
    loader.addEventListener(Event.COMPLETE, onComplete);
    loader.load(request);
}

When you call this function you can use the static GET and POST properties of URLRequestMethod rather than just passing strings for a little bit of extra safety.

Upvotes: 4

Related Questions