Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

simple ajax example with cakephp 2.3.0

please help me, if anyone can give me an example how to use ajax with cakephp 2.3.0 an example is like this

<?php echo $this->html->link('Original', '#', 
                array('onclick'=>'return false;', 'id'=>'remanufactured-link', 'class'=>'get-type-product-link')); ?>   

<div id="content">
</div>

when i click a original link a div with id content is change. how can i do it this with cakephp 2.3.0?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's not much difference to using CakePHP with Ajax than with regular HTML/PHP and Ajax.

Here's an example of an ajax call and response in a Cake APP:

jQuery:

$.ajax({
    url: '/types/fetch/original',
    cache: false,
    type: 'GET',
    dataType: 'HTML',
    success: function (data) {
        $('#context').html(data);
    }
});

(Don't forget to change the url parameter to match your setup).

This will make an ajax request to your Types controller and call the method fetch() with the parameter 'original'.

Your TypesController would look something like this:

class TypesController extends AppController {

    public $components = array(
        'RequestHandler'
    );

    public function fetch($type) {

        $data = $this->Type->find('all', array(
            'conditions'=>array(
                'Type.type'=>$type
            )
        );

        $this->set('data', $data);

    }
}

Adding the RequestHandler component means Cake will automatically use the minimal Ajax layout when rendering your Ajax requests. Usually this is added in AppController so all Controllers can use it.

And the associated view:

/app/View/Types/fetch.ctp

<ul>
    <?php foreach($data as $item): ?>
    <li><?php echo $item['Type']['name']; ?></li>
    <?php endforeach; ?>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...