消息:codeigniter控制器中的未定义变量

时间:2014-01-08 11:28:01

标签: php mysql codeigniter undefined

我使用codeigniter动态获取乡村城市,但我得到以下

错误:消息:未定义的变量:country_id         文件名:controllers / countries.php

我的控制器是:

class countries extends CI_Controller {

public function __construct()
{

    parent::__construct();
    $this->load->model('Countries_model');
}
public function country()
{
    $data=array();
    $this->load->database();
    $data['countries']=$this->Countries_model->get_countries();
    $this->load->view('countries_view',$data);
}   
public function get_cities()
{
    $this->load->model('Countries_model');
$cities = $this->Countries_model->get_cities_by_country_id($country_id);

echo json_encode($cities);

}

查看:

<select id="country" name="country">
<option value="0">Select Country</option>
<?php   foreach($countries as $val)
{
echo '<option   value="'.$val['pkCountry'].'">'.$val['CountryName'].'</option>';

}
?>
</select>

<select id="city" name="city">
<option value="0">Select City</option>
</select>

<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(e) {
$("#country").change(function(e) {
  var selectedValue = $(this).val();
  $.getJSON("/countries/get_cities/" + selectedVal, {}, function(cities) {
    if(cities) {
      $("#city").html("<option value=" + MCity.pkMCity + ">"+ MCity.Name +"</option>"); 
    }
  });
});
});
</script>

型号:

public function get_cities_by_country_id($country_id) {
$this->db->where('fkMCountry', $country_id);
$query = $this->db->get('MCity');

return $query->result();
}

路线:

$route['countries/get_cities'] = 'countries/get_cities';

数据库表 国家:

pkCountry CountryName

城市:

fkMCountry名称

1 个答案:

答案 0 :(得分:0)

第一个 - 控制器

你的控制器应该有第一个字母大写的类名

变化:

class countries extends CI_Controller {

为:

class Countries extends CI_Controller {

此外,在您的代码中,在函数内部

public function get_cities()
{
    $this->load->model('Countries_model');
$cities = $this->Countries_model->get_cities_by_country_id($country_id);

echo json_encode($cities);

}

你引用的参数$ country_id没有传递给那个函数。这就是你得到错误的原因。试试下面,应该消除错误。

public function get_cities($country_id)
    {
        $this->load->model('Countries_model');
    $cities = $this->Countries_model->get_cities_by_country_id($country_id);

    echo json_encode($cities);

    }

第二个 - javascript

您的javascript代码中存在拼写问题导致第二个错误(您在评论中提供)

改变:

var selectedValue = $(this).val();
$.getJSON("/countries/get_cities/" + selectedVal, {}, function(cities)

到:

var selectedValue = $(this).val();
$.getJSON("countries/get_cities/" + selectedValue, {}, function(cities)

第三 - 路由

您的路由定义并不表示uri中将存在第三个段(将您传递给函数的$ country_id参数符号化)。使用下面的内容,它应该最终有效。

$route['countries/get_cities/(:num)'] = 'countries/get_cities/$1';

或者如果您仍有问题,请尝试

$route['countries/get_cities/(:any)'] = 'countries/get_cities/$1';