What's the proper way to serve JSONP with CakePHP?

前端 未结 3 661
南方客
南方客 2020-12-17 02:58

I want to serve JSONP content with CakePHP and was wondering what\'s the proper way of doing it so.

Currently I\'m able to serve JSON content automatically by follow

3条回答
  •  鱼传尺愫
    2020-12-17 03:24

    Ok, I found a solution on this site. Basically you override the afterFilter method with:

    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);
    }
    

    I hope it helps someone else as well.

提交回复
热议问题