简体   繁体   中英

ZF2: What's the easiest way to return a boolean json response?

In ZF1 it was pretty easy to send a json boolean response, for example, in the controller use:

return $this->_helper->json(true);

What's the easiest way to repeat this in ZF2?

I tried creating a new JsonModel with an array of variables. The only entry in the array was my boolean value (with a key of 0). This didn't work because the resolver was still off looking for a template.

I think I somehow need to return early?

EDIT:

I think this is a really important issue. For example, when the JQ Validation plugin uses a server-side validation method, it expects a JSON boolean response.

I managed to make my application JSON-ready by following 'alternate rendering and response strategies' section at the bottom of the Zend\\View page, http://framework.zend.com/manual/2.0/en/modules/zend.view.quick-start.html . But this operates on the array that has been passed to the view, so the boolean true becomes json [true]

I tried the json view helper in various combinations, but couldn't get it to work.

Perhaps I need to create my own rendering and response strategies? That seems like overkill though...

Rob Allen has written an article about it: Returning JSON from a ZF2 controller action

Also you can try this code to return every data without view rendering:

$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent('some data');
return $response;

The easiest way:

echo "true";
exit;

Though you may want to output some appropriate headers.

Arguably the correct way would be to add the JsonStrategy as viewstrategy and use a JsonModel, but I think it always returns an object (the json_encoded associative array of view variables passed to the JsonModel).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM