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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭