I have not yet found a complete example of how to correctly return JSONP using CakePHP 2, so I'm going to write it down. The OP requests the correct path, but its response does not use the native options available in 2.4. For 2.4+, this is the correct method, directly from their documentation:
Customize your views to accept / use JSON ( documentation ):
Router::parseExtensions('json'); routes.php. Cake .json URIRequestHandler ,- Cake , JSON/XML .., , , . :
- URI
/controller/action ( /view/controller/action.ctp), OR - URI
/controller/action.json ( /view/controller/json/action.ctp)
, , , CakePHP _serialize. _serialize Cake (XML, JSON ..), - (). :
- , , i.e.
$this->set('post', $post); - Cake, XML, JSON ..,
$this->set('_serialize', array('posts'));, - ,
. Cake. JSONP ():
- Cake, JSONP,
$this->set('_jsonp', true);, Cake , . .
, , Cake .json, , JSONP:
public function getTheFirstPost()
$post = $this->Post->find('first');
$this->set(array(
'post' => $post, <-- Set the post in the view
'_serialize' => array('post'), <-- Tell cake to use that post
'_jsonp' => true <-- And wrap it in the callback function
)
);
JS:
$.ajax({
url: "/controller/get-the-first-post.json",
context: document.body,
dataType: 'jsonp'
}).done(function (data) {
console.log(data);
});