任务:当我从select tag customer(我有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 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>
答案 0 :(得分:1)
从您的帖子中很难理解问题出在客户端还是服务器端......
在您的第一个示例中,您没有在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 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);
}