Skip to content
torleif edited this page Nov 19, 2010 · 5 revisions

To use amf.js start by dumping some AMF into an HTTP response. In Java with BlazeDS I did this:

bc. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    response.setHeader("Content-Type", "application/x-amf;charset=x-user-defined");
    ServletOutputStream out = response.getOutputStream();
    ActionMessage requestMessage = new ActionMessage(MessageIOConstants.AMF3);
    MessageBody amfMessage = new MessageBody();
    amfMessage.setData(someSerializableObject);
    requestMessage.addBody(amfMessage);
    AmfMessageSerializer amfMessageSerializer = new AmfMessageSerializer();
    amfMessageSerializer.initialize(SerializationContext.getSerializationContext(), out, new AmfTrace());
    amfMessageSerializer.writeMessage(requestMessage);
    out.close();
}

In a HTML web page add the amf.js script:

<script type="text/javascript" src="amf.js"></script>

In JavaScript make a XHR request for some data:

bc.. var url = "TestServlet";
var req;

function getAMF()
{
    if (window.ActiveXObject)
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        req = new XMLHttpRequest();
        //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
        req.overrideMimeType('text/plain; charset=x-user-defined');
    }
    req.onreadystatechange = processReqChange;
    req.open("GET", url, true);
    req.send(null);
}

And when the response comes back decode the AMF:

bc. function processReqChange()
{
    if (req.readyState == 4)
    {
        if (req.status == 200)
        {
            var o = decodeAMF(req.responseText).messages[0].body;
        }
        else
        {
            alert("There was a problem retrieving the data:\n" + req.statusText);
        }
    }
}

If you require encoding of objects, you may want to have a look at Torleif's fork. Firefox is the only browser that works 100%, as most other browsers don’t support byte arrays.

To encode data, try the following:

function ExampleVO()
{
}

function loopResult(l) {
    for (var i = 0; i < l.length; i ++) {
        if (l[i] instanceof ExampleVO) {
            console.log('responded with ExampleVO') ;
        }
    }
}

window.onload = function () {
    registerClassAlias("mynamespace.ExampleVO", ExampleVO);

    // create service remoting object
    service = new RemotingProxy("gateway.php", 'mynamespace.MyService', amf.ObjectEncoding.AMF3);

    service.addHandler('getData',
		 loopResult(r),  // success
		function(e){console.log('error ' + e)}); // failure

    // you can also pass in objects, numbers, arrays etc here
    service.getData();
}
Clone this wiki locally