我一直在徒劳地尝试用 CakePHP 和 AJAX 实现动态选择框。
看法:
索引.ctp
<?php
echo $this->Html->script('jquery-1.6.3.min.js');
echo $this->Html->script('prototype', array('inline' => false));
echo $this->Js->writeBuffer();
?>
<?php $this->Form->create('Supplier'); ?>
<?php echo $this->Form->input('categorie_id',array('type'=>'select','label' => false,'options'=>$categories,'class'=>'custom-dropdown__select custom-dropdown__select--white'));?>
<?php echo $this->Form->input('premieresc_id',array('type'=>'select','label' => false,'class'=>'custom-dropdown__select custom-dropdown__select--white'));?>
<?php $this->Form->end();
$this->Js->get('#CategorieId')->event('change', $this->Js->request(
array('controller' => 'suppliers', 'action' => 'getPremierescs'),
array(
'update' => '#PremierescId',
'async' => true,
'dataExpression' => true,
'method' => 'post',
'data' => $this->Js->serializeForm(array('isForm' => false, 'inline' => true))
)));
?>
ajax_dropdown.ctp
<?php foreach($premieres as $k => $v) { ?>
<option value="<?php echo $k; ?>"><?php echo $v; ?></option>
<?php } ?>
控制器:
<?php
class SuppliersController extends Controller {
var $name = 'Suppliers';
public $helpers = array('Js');
var $components = array('RequestHandler','Session');
public function index() {
$this->loadModel('Premieresc');
$this->loadModel('Categorie');
$categories = $this->Categorie->find('list', array('fields' => array('Categorie.id','Categorie.categorie_label')));
$premieres=array();
$this->set(compact('premieres', 'categories'));
$this->layout = 'ajax';
}
function getPremierescs() {
$premieres = $this->Premieresc->find('list',array('conditions' => array('Premieresc.id_cat' => $this->request->data['Categorie']['id'],
'fields' => array('Premieresc.id','Premieresc.level1_label'))));
$this->set(compact('premieres'));
$this->layout = 'ajax';
$this->render('/suppliers/ajax_dropdown', 'ajax');
}
这些是模型:
<?php
class Premieresc extends AppModel {
var $name = 'Premieresc';
public $id;
public $level1_label;
public $belongsTo = array('Categorie' => array('className' => 'Categorie',
'foreignKey' => 'id_cat'));
public $hasMany = array(
'Deuxieme' => array('className' => 'Deuxiemesc',
'foreignKey' => 'id_level1'));
}
?>
<?php
class Categorie extends AppModel {
var $name = 'Categorie';
public $id;
public $categorie_label;
public $hasMany = array(
'Premieresc' => array(
'className' => 'Premieresc',
'foreignKey' => 'id_cat'
)
);
}
?>