couldn't find an answer via search (or google) so i'll ask it myself. is it possible to handle JSONP calls to the zend framework?
only found this page:
http://framework.zend.com/wiki/display/ZFPROP/Zend_Json_Server+-+Lode+Blomme
but i'm not s开发者_JS百科ure if it is already implemented!?
thx
JSONP is just a JSON response that is wrapped in a specified callback function that is executed on the client.
Zend_Json_Server is only for JSON-RPC at the moment. The link you found is an archived (unimplemented) proposal to add JSONP support.
The good news is that you don't need any sort of framework to support JSONP. Assuming $response
is the data you wish to return to the user, and $callback
contains the sanitized callback:
echo $callback, '(', json_encode($response), ');';
Tada, you've JSONP'd.
Please take care to read the document I linked about sanitizing the callback. Failure to sanitize the callback may result in an exploitable condition.
for those of you that are using ZEND framework and want to know what i had to change in order to get this working ...
had to make changes on a couple of files:
1) added a new layout under VIEWS > LAYOUTS called json.phtml
<?php
header('Content-type: application/javascript');
echo $this->layout()->content;
?>
2) controller
added a new action called jsonAction
public function jsonAction()
{
$this->_helper->layout->setLayout('json');
$callback = $this->getRequest()->getParam('callback');
if ($callback != "")
{
// strip all non alphanumeric elements from callback
$callback = preg_replace('/[^a-zA-Z0-9_]/', '', $callback);
}
$this->view->callback = $callback;
// ...
}
3) added a new view under VIEWS > SCRIPTS > json.phtml
<?php
if ($this->callback != "")
{
echo $this->callback, '(', json_encode($response), ');';
}
else
{
echo json_encode($response);
}
?>
now i can make an ajax call via jquery like this:
$.ajax({
type: "GET",
url: 'http://<your_url>/<your_controller>/json',
data: {},
dataType: "jsonp",
success: function(json) {
console.log("success");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("error("+jqXHR+", "+textStatus+", "+errorThrown+")");
}
});
maybe this helps someone ...
精彩评论