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 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.

    点赞 评论 复制链接分享

相关推荐