我正在使用 CakePHP 2.7.8。我想使用 Ajax 更新列表中的相关列表。
我在项目中的数据库和模型中有一个customers
表和表。customer_addresses
customers
customerAddress
还有另一个控制器serviceRequests
,我必须customer
从数据库中的 CakePHP 生成的下拉列表中选择所选客户的地址。
我做了什么-我getCustomerAddress
在serviceRequests
控制器中添加了一个功能
public function getCustomerAddress(){
$customer_id = $this->request->data['Post']['customer_id'];
$customer_address = $this->CustomerAddress->find('list',array(
'condition' => array('CustomerAddress.customer_id' => $customer_id),
'recursive' => -1
));
$this->set('customerAddresses', $customer_address);
$this->layout = 'ajax';
}
要显示检索到的数据,我有一个视图get_customer_address.ctp
<?php
foreach ($customerAddresses as $key => $value): ?>
<option value="<?php echo $key;?>"><?php echo $value; ?></option>
<?php endforeach; ?>
在功能控制器的add.ctp
视图中,我最后添加了以下脚本。serviceRequests
add
<div class="serviceRequests form">
<?php echo $this->Form->create('ServiceRequest'); ?>
<fieldset>
<legend><?php echo __('Add Service Request'); ?></legend>
<?php
echo $this->Form->input('customer_id');
echo $this->Form->input('customer_address_id');
echo $this->Form->input('status');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<?php
$this->Js->get('#ServiceRequestCustomerId')->event('change',
$this->Js->request(array(
'controller' => 'serviceRequests',
'action' => 'getCustomerAddress'
), array(
'update' => '#ServiceRequestCustomerAddressId',
'async' => true,
'method' => 'post',
'dataExpression' => true,
'data' => $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
?>
并渲染Js
,我已将以下代码添加到最后一个default.ctp
<!-- script for layout -->
<?php echo $scripts_for_layout; ?>
<!-- Js writeBuffer -->
<?php
if(class_exists('JsHelper') && method_exists($this->Js, 'writeBuffer')) echo $this->Js->writeBuffer ();
// writes cached scripts
?>
但是在访问localhost/serviceRequests/add
ajax 调用时不起作用,所有客户的姓名和所有客户的地址都显示在列表中。