dqxafj6830 2015-02-08 12:16
浏览 18
已采纳

CakePHP - ajax-requests的布局文件夹

i will have two different request types for my application, AJAX and JSON. AJAX shall output html-code; JSON shall return pure JSON Code. I managed to send JSON Output by calling controller actions like this: /index.json --> Outputs json code, view lies under /View/Test/json/index.ctp

How do i manage to store the view files in /View/Test/ajax/index.ctp for a request like /index.ajax

I tried setting Router::parseExtensions('json', 'ajax'); in my /Config/routes.php but then callling index.ajax just outputed the standard /View/Test/index.ctp insetad of /View/Test/ajax/index.ctp

What am I doing wrong?

With kind regards,

Battlestr1k3

  • 写回答

1条回答 默认 最新

  • dongyan5641 2015-02-08 18:10
    关注

    Ajax is a method, not a data type.

    You may be making an ajax request which will return json in which case you can use it in a json view or decode it and use it in a standard view.

    If you are retuning a json object or array via your ajax request to display as HTML you can also parse it with jquery. See here for more information:

    http://api.jquery.com/jquery.parsejson/

    Edit following comments:

    First, you need to have a view file to output the HTML, this will be in:

    app/View/Tests/index.ctp app/View/Tests/add.ctp

    etc

    You then have a corresponding method in your controller:

    public function index(){
      //index method here
    }
    

    At this point your index view will render when you go to /tests/index.html in your browser, and all the HTML structure you have set in the index.ctp file will be showing. However you will have no data as you have not retrieved it from the database or set it for your view to use.

    So, to render it you run your ajax call and set the url as /Tests/index

    Then add the logic to your index function in your controller something like:

    if($this->RequestHandler->isAjax()){
      //debug can cause problems with AJAX requests so switch it off if it is on
      Configure::write('debug', 0);
    
    //you need to pass the id through in the data parameter of your ajax call  
    $id = $this->request->query['id'];
    
      $settings = array(
        'conditions' => array('Test.id' => $id),
      ); 
      $data = $this->Test->find('first', $settings);
    
      return json_encode($data);
    }
    

    This will return a json array which you can parse with jquery and append to your HTML.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码