CakePHP Ajax:更新列表,并在相关列表

时间:2016-02-02 16:25:23

标签: cakephp cakephp-2.x cakephp-2.7 cakephp-ajaxhelper

我正在开发CakePHP 2.7.8。我想使用Ajax更新列表中的相关列表。

我在数据库中有一个customers表和customer_addresses表,项目中有customerscustomerAddress个模型。

还有另一个控制器serviceRequests,我必须从CakePHP从数据库生成的下拉列表中选择customer和所选客户的地址。

我做了什么 - 我在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呼叫无效,所有客户的姓名和所有客户的地址都显示在列表中。

1 个答案:

答案 0 :(得分:1)

这是如何使用cake http://sandbox.dereuromark.de/sandbox/ajax_examples/chained_dropdowns实现链式选择的示例   - 该示例的相关文章位于http://www.dereuromark.de/2014/01/09/ajax-and-cakephp/