Codeigniter选择框值未使用Ajax传递给控制器

Codeigniter选择框值未使用Ajax传递给控制器

本文介绍了Codeigniter选择框值未使用Ajax传递给控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将选择框的值传递给 controller ,但该值未传递
我的代码

Am trying to pass the select-box value to controller but value not passThis is my code

<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将值传递给控制器​​?

How can i pass the value to controller using ajax ?

推荐答案

请按照以下说明对您的代码做一些更改

Pls do make some changes in ur code as follows

<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

I think this is only the reference code for getting an idea about how to pass data to controller and return the result to the view page using ajax and 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));

    }
} ?>

我希望这会对您有所帮助。谢谢!

I hope this may helps you. Thanks!

这篇关于Codeigniter选择框值未使用Ajax传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:06