Return JSON or JSONP rename

author:

contributor:

published:

updated:

source uri:

Summary

In order to return JSON or JSONP, you need to use a "script" file, not a "template" file. In the...

Content

In order to return JSON or JSONP, you need to use a "script" file, not a "template" file. In the script file, you just need


> acre.response.status = 200;
> acre.response.set_header("content-type", "application/json");
> acre.write(JSON.stringify(o));


where `o` is a Javascript variable that is not undefined.

To support JSONP with the callback URL parameter named `callback`, follow this pattern:

> acre.response.status = 200;
> acre.response.set_header("content-type", "application/json");
>
> var callback = acre.environ.params["callback"];
> if (callback) {
> acre.write(callback + "(");
> }
>
> acre.write(JSON.stringify(o));
>
> if (callback) {
> acre.write(")");
> }

If you want the JSON string to be readable (formatted on multiple lines and indented), use `JSON.stringify(o, null, 2)`.

Created by: dfhuynh via Cookbook Jun 3, 2009
Last edited by: dfhuynh via Cookbook Jul 9, 2009

Recent Discussions about Return JSON or JSONP

There is no discussion about this document.

Start the Discussion »
Explore the Data
View all the data we have for Return JSON or JSONP
Flag this Document
Why do you want to flag this document?