2012-12-24 12 views
6

任務:當我從選擇標籤客戶(我有customer_id)中選擇時,它必須向DB請求並返回所有客戶字段。然後它必須自動填充一些輸入。我嘗試製作ajax + jQuery。 Ajax很好。它正在工作!阿賈克斯響應錯誤的方式

這裏的JS:

我想出解決辦法:

<script> 
$(document).ready(function() { 
    $('#customer_load').change(function() { 
     $.ajax({ 
      url: '<?= $this->url(array('action' => 'ajax', 'controller' => 'baza')) ?>', 
      type: 'POST', 
      dataType: 'json', 
      data: { 
        // list of request parameters 
        'customer_id': $(this).attr('value') 
      }, 
      success: function(data) { 
        //alert(data.current_discount); 
        $('#extra_discount').val(data.extra_discount); 
        $('#current_discount').val(data.current_discount); 
        $('#customer_number').val(data.customer_id); 
      } 
     }); 
    }); 
}); 

PHP初始化:

$this->_helper->AjaxContext()->addActionContext('add', 'json')->initContext('json'); 

阿賈克斯行動:

$id= $this->_getParam('customer_id'); 
$result = $this->_customers->fetchSelected($id); 
$this->view->customers = $result; 
$this->_helper->json($result); 

HTML:

<select name="customer_id" id="customer_load" style="width:300px;"> 
    <option value="0">Выберите заказчика</option> 
     ?php foreach ($this->customers as $cus): ?> 
    <option value="<?= $cus['customer_id'] ?>"" <?php if ($cus['customer_id'] == $this->form_data['customer_id']) echo "selected"; ?> ><?= $cus['lastname'] . " " . $cus['name'] ?></option> 
    <?php endforeach; ?> 
    <option value="new" onclick="NewCustomer()">Новый заказчик</option> 
    </select> 
+0

爲了解決Ajax調用'/ add'中給定的URL,你是否使用了某種類型的mod重寫? – dbf

+0

暫時禁用'isXmlHttpRequest'檢查控制器,並首先在瀏覽器中直接測試您的ajax操作。一旦你得到它的工作增加安全條件,並實施你的阿賈克斯調用。 – Alex

+0

感謝亞歷克斯的建議,我改變URL以「/巴扎/加」,但在我的螢火蟲是 POST http://www.voskmodel.dev/baza/add \t 200確定爲65μs 我猜CUSTOMER_ID發送無處 – Stopper

回答

1

從您的帖子很難理解,如果這個問題是在客戶端或服務器端... 在你不使用你的Ajax請求customer_id你的第一個例子,你不需要值轉換爲Number在JavaScript中。

使用AJAX請求下圖:

$(document).ready(function(){ 
    $.ajax({ 
    url: <?= $this->url(array('action' => 'add', 'controller' => 'baza')) ?>, 
    type: 'POST', 
    dataType: 'json', 
    data: { 
     // list of request parameters 
     'customer_id': $('select[name=customer_id] option:selected').val(), 
    }, 
    success: function(results){ 
     // analyze your response and add custom logic 
     console.debug(result); 
    } 
    }); 
}); 

根據你的PHP代碼,你是過於複雜的事情。 當你試圖讓它工作時(這種方式你可以在瀏覽器中直接測試baza/add),在行動頂部添加你的支票,並在評論它們之後發表評論,一旦你取消評論和測試工作。使用JSON view helper輸出json。

public function addAction() 
    { 
     // checks/validation/etc 

     // do some processing...    
     $result = $this->_customers->fetchSelected($id); 

     // Send the JSON response: 
     $this->_helper->json($result); 
    } 
+0

我終於做到了,你可以看看在代碼。謝謝! – Stopper