tombenner / wp-mvc

An MVC framework for WordPress
http://wpmvc.org
MIT License
625 stars 171 forks source link

Recommended way to return a JSON #204

Closed ivamluz closed 6 years ago

ivamluz commented 6 years ago

In case I create an action that returns either HTML or JSON (depending on the content-type header), is there a recommended way to return JSON content?

Should I create a view that is responsible for encoding the data as JSON or is there any method in the controller that can be called directly to return JSON, instead of setting a parameter in the view?

cyberscribe commented 6 years ago

I do this all the time. I do it in the controller. I just send a json content type header, echo a json_encode of an array or object, and add a die statement to prevent the view rendering.

You can switch on a $param (get line) or anything else you want to determine json output.

HTH!

On 2 February 2018 at 11:48, Ivam notifications@github.com wrote:

In case I create an action that returns either HTML or JSON (depending on the content-type header), is there a recommended way to return JSON content?

Should I create a view that is responsible for encoding the data as JSON or is there any method in the controller that can be called directly to return JSON, instead of setting a parameter in the view?

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/tombenner/wp-mvc/issues/204, or mute the thread https://github.com/notifications/unsubscribe-auth/AAqV5Q_XxVyKgjgH8J-tWPBAxITld0CIks5tQvYlgaJpZM4R3El3 .

secretcoder commented 1 year ago

@cyberscribe How to you set the content type header? Having no luck on setting it.

cyberscribe commented 1 year ago

header('Content-type: application/json'); echo json_encode([]); die();

secretcoder commented 1 year ago

@cyberscribe Very nice framework, I will use it to implement a Product Catalog CMS. Thank you.