Ajax Response

bosok | 3 years ago

What is the preferred way to generate an ajax response without using a view? I would like to call a controller method and have it return some data as JSON. Is there already a way to do this or would I have to write my own JsonResponse (how would I avoid using a view)?

cheers.



KrisJordan | 3 years ago

This is going to be improved in 0.20 and the bits should be up on Edge shortly. Currently working on the unstable branch content-negotiation if you want to play with fire :)

The simple solution 0.12 and below is to simply tack '.json' onto the end of a URL. The caveat is that this may dump more information than you want. You can hack around this by creating your own subclass of NativeView and filtering data there.

Good RESTful practice suggests that the data you send to JSON and the data you send to a template, for the same URL, should be pretty much the same data (a proper subset may go to JSON).

In 0.20 the default view no longer tries to automatically render JSON/XML. Instead, the default view system now looks for files with extensions that match the format of the request. So, if you requested localhost/something.json (or localhost/something with an Accepts header of application/json) the default view system looks for a view named your-view.json.php (instead of your-view.php)

On top of that, multiple views can be registered with a controller and be selected based on the requested content type. So controllers could also have an AutoJSON view that overrides JSON requests and automatically converts to JSON.

There will be a better, more detailed example-driven doc on this once the code wraps up.

reply



Welcome KrisJordan!

Web: http://www.krisjordan.com/

Location: North Carolina

Edit Profile