This is nice in a heavy Ajax application – you can use the same data format on the request and the response.
You might not have been aware that prototype’sprototype’s Ajax.Request can send a postBody, instead of parameters.
So if you don’t mind all of your Ajax requests being POSTs (I don’t), you can just ignore serializing parameters and just stick JSON in the postBody.
This makes my jsunit tests (and therefore my production code) nicer:
BEFORE:
<code> function testRequest() { var settings = {volume:"high", color:"red"} var command = new SaveSettings(settings); assertEquals("/save_settings", command.asAjaxPayload().url); assertEquals("volume=high&color=red", command.asAjaxPayload().parameters); } </code>
AFTER:
<code> function testRequest() { var settings = {volume:"high", color:"red"} var command = new SaveSettings(settings); assertEquals("/save_settings", command.asAjaxPayload().url); assertEquals(settings, JSON.parse(command.asAjaxPayload().postBody)); } </code>
(and of course, you can push the stringifying of the post body down a layer, to get rid of the JSON.parse at this level)
About the Author