What is the correct way to serve JSONP with CakePHP?

I want to serve JSONP content with CakePHP and wondered how to do it right.

Currently, I can automatically download JSON content by following this CakePHP tutorial .

+5
source share
3 answers

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 URI
    • RequestHandler ,
    • 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 ():

  1. 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);
});
+4

, . afterFilter :

public function afterFilter() {
    parent::afterFilter();

    if (empty($this->request->query['callback']) || $this->response->type() != 'application/json') {
        return;
    }

    // jsonp response
    App::uses('Sanitize', 'Utility');
    $callbackFuncName = Sanitize::clean($this->request->query['callback']);
    $out = $this->response->body();
    $out = sprintf("%s(%s)", $callbackFuncName, $out);
    $this->response->body($out);
}

, - .

+5

CakePHP 2.4 .

http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#jsonp-response

, :

$this->set('_jsonp', true);

.

:

/**
 *
 * beforeRender method
 *
 * @return void
 */
    public function beforeRender() {
        parent::beforeRender();
        $this->set('_jsonp', true);
    }
0

All Articles