Ajax与codeigniter中的选择框

时间:2015-04-12 18:39:56

标签: javascript php jquery ajax codeigniter

我有一个带有两个选择框的表单。一个是城市,另一个是该地区。

我的要求。当某人选择一个城市时,必须从数据库中捕获城市中的区域并显示在另一个选择框中。

我试过但是,我的ajax有问题。这是我的代码。

查看

                                    <div class="location-group">
                                    <label class="-label" for="city">
                                        Location
                                    </label>
                                    <div class="">
                                        <select id="city_select">
                                            <option value="0"> select</option>
                                            <?php foreach ($city as $cty) : ?>
                                            <option value="<?php echo $cty->city_id; ?>"><?php echo $cty->name; ?></option>
                                            <?php endforeach ?>
                                        </select>
                                    </div>
                                </div>


                                <div class="location control-group" id="area_section">
                                    <label class="control-label" for="area">
                                        Area
                                    </label>
                                    <div class="controls">
                                        <select id="area_select">
                                            <option value=""> Any</option>
                                            <?php foreach ($area as $ara) : ?>
                                            <option value="<?php echo $ara->ara_id; ?>"><?php echo $ara->name; ?></option>
                                            <?php endforeach ?>
                                        </select>
                                    </div><!-- /.controls -->
                                </div><!-- /.control-group -->

控制器

function __construct() {
    parent::__construct();

  //session, url, satabase is set in auto load in the config

    $this->load->model('Home_model', 'home');
    $this->load->library('pagination');


}



function index(){
    $data['city'] =  $this->home->get_city_list();
    $data['type'] =  $this->home->get_property_type_list();
    $this->load->view('home', $data);
}


function get_area(){
    $area_id = $this->uri->segment(3);
    $areas =  $this->home->get_area_list($area_id);
    echo json_encode($areas);
}

模型

function get_area_list($id){
  $array = array('city_id' => $id, 'status' => 1);
  $this->db->select('area_id, city_id, name');
  $this->db->where($array);
  $this->db->order_by("name", "asc"); 
  $this->db->from('area'); 
  $query = $this->db->get();
  $result = $query->result();
  return $result;
}

的Ajax

<script type="text/javascript">
$('#area_section').hide();


    $('#city_select').on('change', function() {
     // alert( this.value ); // or $(this).val()
      if (this.value == 0) {
        $('#area_section').hide(600);
      }else{


        //$("#area_select").html(data);
            $.ajax({
                  type:"POST",
                  dataType: 'json',
                  url:"<?php echo base_url('index.php?/home/get_area/') ?>",
                  data: {area:data},
                  success: function(data) {
                    $('select#area_select').html('');
                    $.each(data, function(item) {
                        $("<option />").val(item.area_id)
                                       .text(item.name)
                                       .appendTo($('select#area_select'));
                    });
                  }
                });


        $('#area_section').show(600); 
      };



    });
</script>

一旦我选择了一个城市,它必须从数据库中获取城市中的所有区域,并将其显示在 area_select 选择框中。

任何人都可以帮助我。感谢。

2 个答案:

答案 0 :(得分:1)

尝试改变这种方式。

您的ajax代码

//keep rest of the code
 $.ajax({
              type:"POST",
              dataType: 'json',
              url:"<?php echo base_url('index.php?/home/get_area/') ?>",
              data: {area:$(this).val()},//send the selected area value

同时显示ajax成功函数中的area_section

您的控制器功能

function get_area()
{
   $area_id = $this->input->post('area');
   $areas =  $this->home->get_area_list($area_id);
   echo json_encode($areas);
}

希望它能解决你的问题

<强>更新
尝试使用像这样的ajax更新功能

 success: function(data) {
                $('select#area_select').html('');
                for(var i=0;i<data.length;i++)
                {
                    $("<option />").val(data[i].area_id)
                                   .text(data[i].name)
                                   .appendTo($('select#area_select'));
                }
              }

答案 1 :(得分:0)

按照此页面上的说明进行操作的简单方法


https://itsolutionstuff.com/post/codeigniter-dynamic-dependent-dropdown-using-jquery-ajax-exampleexample.html


demo_state table:

CREATE TABLE `demo_state` (
  `id` int(11) NOT NULL,
  `name` varchar(155) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

demo_cities表:

CREATE TABLE `demo_cities` (
  `id` int(11) NOT NULL,
  `state_id` int(12) NOT NULL,
  `name` varchar(155) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

成功创建数据库和表之后,我们必须在Codeigniter 3应用程序中配置数据库,因此打开database.php文件并添加您的数据库名称,用户名和密码。

application / config / database.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


$active_group = 'default';
$query_builder = TRUE;


$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'database' => 'test',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

另请参阅:如何在Laravel 5中使用jquery ajax进行简单的依赖下拉? 步骤3:添加路线

在此步骤中,您必须在我们的路线文件中添加两条新路线。我们将管理ajax的布局和另一条路线,因此让我们将路线作为以下代码:

application / config / routes.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;


$route['myform'] = 'HomeController';
$route['myform/ajax/(:any)'] = 'HomeController/myformAjax/$1';

第4步:创建控制器

好吧,现在首先我们必须使用索引方法创建一个新的控制器HomeController。因此,请在此路径application / controllers / HomeController.php中创建HomeController.php文件,并将以下代码放入此文件中:

application / controllers / HomeController.php

<?php


class HomeController extends CI_Controller {


   /**
    * Manage __construct
    *
    * @return Response
   */
   public function __construct() { 
      parent::__construct();
      $this->load->database();
   }

   /**
    * Manage index
    *
    * @return Response
   */
   public function index() {
      $states = $this->db->get("demo_state")->result();
      $this->load->view('myform', array('states' => $states )); 
   } 

/ **     *管理uploadImage     *     * @返回响应    * /

   public function myformAjax($id) { 
       $result = $this->db->where("state_id",$id)->get("demo_cities")->result();
       echo json_encode($result);
   }

}

?> 第5步:创建查看文件

在此步骤中,我们将创建myform.php视图,在这里,我们将创建带有两个下拉选择框的表单。我们还在这里编写ajax代码:

application / views / myform.php

<!DOCTYPE html>
<html>
<head>
    <title>Codeigniter Dependent Dropdown Example with demo</title>
    <script src="http://demo.itsolutionstuff.com/plugin/jquery.js"></script>
    <link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/bootstrap-3.min.css">
</head>


<body>
<div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">Select State and get bellow Related City</div>
      <div class="panel-body">


            <div class="form-group">
                <label for="title">Select State:</label>
                <select name="state" class="form-control" style="width:350px">
                    <option value="">--- Select State ---</option>
                    <?php
                        foreach ($states as $key => $value) {
                            echo "<option value='".$value->id."'>".$value->name."</option>";
                        }
                    ?>
                </select>
            </div>


            <div class="form-group">
                <label for="title">Select City:</label>
                <select name="city" class="form-control" style="width:350px">
                </select>
            </div>


      </div>
    </div>
</div>


<script type="text/javascript">


    $(document).ready(function() {
        $('select[name="state"]').on('change', function() {
            var stateID = $(this).val();
            if(stateID) {
                $.ajax({
                url:"<?php echo base_url('index.php/Diplome/myformAjax/') ?>"+ stateID,

                    //url: '/myform/ajax/'+stateID,
                    type: "GET",
                    dataType: "json",
                    success:function(data) {
                        $('select[name="city"]').empty();
                        $.each(data, function(key, value) {
                            $('select[name="city"]').append('<option value="'+ value.id +'">'+ value.name +'</option>');
                        });
                    }
                });
            }else{
                $('select[name="city"]').empty();
            }
        });
    });
</script>


</body>
</html>