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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动