【问题标题】:Json does not popup as download file in cakephp 2.3Json 不会在 cakephp 2.3 中作为下载文件弹出
【发布时间】:2013-05-25 19:57:21
【问题描述】:

我正在使用 cakephp 2.3 并希望生成 json 格式的用户列表。

控制器名称:用户 方法:列表

早些时候,我在 cake 1.3.x 中完成了它,当用户在浏览器中尝试通过 url 访问方法时,输出作为下载文件出现,但是当我在 cakephp 2.3 中执行此操作时,它会在浏览器页面本身上显示 json 输出而不是下载文件。

这是我的代码:

控制器:

<?php
      App::uses('AppController', 'Controller');
class UsersController extends AppController {
      public $helpers = array('Form', 'Html', 'Js', 'Time');
      public $components = array('RequestHandler');
      var $layout = 'js/default';

public function list() {
            $this->log("i got data in user add:");
        $this->log($this->request->data);
        $posts['id']['name']='kapil';
        $this->set(compact('posts'));

    }
}

list.ctp 文件

<?php echo json_encode(compact('posts')); ?>

查看/js/default.ctp

<?php echo $scripts_for_layout; ?>
<?php echo $this->fetch('content'); ?>

当我尝试在浏览器中访问我的功能时,我得到了这个输出

url: http://localhost/project/users/list

{"posts":{"id":{"name":"aditya"}}} 

这个输出是正确的,但应该是下载文件格式。我不知道这里出了什么问题。

【问题讨论】:

  • 你想强制浏览器下载文件而不是渲染它吗?
  • 是的!我要下载它

标签: cakephp cakephp-2.0


【解决方案1】:

如果您尝试强制下载,您的代码必须使用 Response 对象。

这是取自CsvExport Behavior的示例:

   public function export() {
        $this->autoRender = false;
        $modelClass = $this->modelClass;
        $this->response->type('Content-Type: text/csv');
        $this->response->download( strtolower( Inflector::pluralize( $modelClass ) ) . '.csv' );
        $this->response->body( $this->$modelClass->exportCSV() );
    }

所以你的代码应该是这样的:

   public function list() {

        $this->autoRender = false;

        $this->log("i got data in user add:");
        $this->log($this->request->data);

        $posts['id']['name']='kapil';
        $this->set(compact('posts'));
        $modelClass = $this->modelClass;

        $this->response->type('Content-Type: application/json');
        $this->response->download('list.json');
    }

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2010-11-07
    • 1970-01-01
    相关资源
    最近更新 更多