我试图将select-box
值传递给controller
但值不通过
这是我的代码
<select class="form-control" name="product_id" onchange="getProduct(this.value)">
<option>--Select Payment--</option>
<option value="<?php echo $product['sno']; ?>"><?php echo $product['product_name']; ?></option>
</select>
<script type="text/javascript">
function getProduct(product_id) {
$.ajax({
url: "<?php echo base_url(); ?>customer_order/getproduct",
type: "POST",
data: {
id: product_id,
}
}).done(function(data) {
$('product_id').val(data);
alert(product_id);
});
}
</script>
控制器:
class Customer_order extends CI_Controller {
function getproduct(){
$data = $this->input->post('id');
echo '<script type="text/javascript">alert("'.$data.'");</script>';
$this->load->view('create_customer_order',$data);
}
}
如何使用ajax将值传递给控制器?
答案 0 :(得分:1)
请在ur代码中进行一些更改,如下所示
<select class="form-control" name="product_id" id="product_id">
<option>--Select Payment--</option>
<?php foreach($product as $prod){ ?>
<option value="<?php echo $prod['sno']; ?>"><?php echo $prod['product_name']; ?></option>
<?php } ?>
</select>
<script>
$('#product_id').on('change', function(){
var proId = $('#product_id option:selected').val();
if(proId != null){
var url = "<?php echo base_url(); ?>customer_order/getproduct";
var proResult = $.ajax({
url: url,
data: {'id': proId },
type: 'post',
dataType: 'json'
});
proResult.done(function(data){
// console.log('data', data);
// alert(data);
// Here..Do something as you wish
});
}
});
</script>
我认为这只是一个参考代码,用于了解如何将数据传递给控制器并使用ajax和json将结果返回到视图页面
在控制器中应该有功能
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Customer_order extends CI_Controller {
function __construct() {
parent::__construct();
}
function getproduct() {
$data = $this->input->post('id', true);
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($data));
}
} ?>
我希望这对你有所帮助。谢谢!