簡體   English   中英

Ajax與codeigniter中的選擇框

[英]Ajax with select box in 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;
}

阿賈克斯

<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選擇框中。

誰能幫幫我嗎。 謝謝。

嘗試改變這種方式。

您的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'));
                }
              }

遵循此頁面上的說明的簡單方法


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文件,並將以下代碼放入此文件中:

應用程序/控制器/ 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代碼:

應用程序/視圖/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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM