Ajax响应出错了


Ajax response is going wrong way

任务:当我选择从选择标签客户(我有customer_id),它必须得到请求进入DB并返回所有客户字段。然后它必须自动填充一些输入。我尝试使ajax+jQuery。Ajax很好。现在起作用了!

JS:

I figure out:

<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 init

:

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

Ajax动作:

$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>

从你的帖子很难理解问题是在客户端还是服务器端…在你的第一个例子中,你没有在ajax请求中使用customer_id,你不需要在javascript中将值转换为Number

使用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视图辅助器输出JSON .

   public function addAction() 
   {
        // checks/validation/etc
        // do some processing...               
        $result = $this->_customers->fetchSelected($id);
        // Send the JSON response:
        $this->_helper->json($result);
   }