简体   繁体   English

从控制器获取Json数据

[英]Get Json data from controller

I need to create dinamic select into my form. 我需要在表单中创建动态选择。 I have wrote this code to get it dinamically from my controller (CodeIgniter) that get data from model. 我已经编写了这段代码,以便从我的控制器(CodeIgniter)上从模型中获取数据。

This is the script: 这是脚本:

<script type="text/javascript">
   $(document).ready(function(){
                    $("select#regione").change(function(){
                        $.getJSON("http://test:8888/ricerca/test",{id: $(this).val()}, function(dati){
                            var options = '';
                            for (var i = 0; i < dati.length; i++) {
                                options += '<option value="' + dati[i].valore + '">' + dati[i].etichetta + '</option>';
                            }
                            $("#provincia").html(options);
                            $('#provincia option:first').attr('selected', 'selected');
                        });
                    });
                });
            </script>

This is the dropdown form: 这是下拉表格:

<form action="base_url().'ricerca'" method="post">
<select name="regione" id="regione">
<option value="">No option</option>
<option value="Lombardia">Lombardia</option>
<option value="Lazio">Lazio</option>
</select>

<select name="provincia" id="provincia">
</select>
</form>

and this is the controller: 这是控制器:

class Ricerca extends CI_Controller
{
 public function test()
{
 $dati = array();
         array_push($dati,array("valore"=>"ciao", "etichetta"=>"ciao"));
         array_push($dati,array("valore"=>"mamma", "etichetta"=>"mamma"));
         return json_encode($dati);
}
}

Before to do my query in the model I would see if my script works but if I select an option in the first select called "Regione" the script does nothing 在模型中进行查询之前,我会先查看我的脚本是否有效,但是如果我在第一个选择的“ Regione”中选择了一个选项,则脚本不会执行任何操作

you have to echo json data from controller function not to return data 您必须从控制器功能回显json数据而不返回数据

public function test()
{
 $dati = array();
         array_push($dati,array("valore"=>"ciao", "etichetta"=>"ciao"));
         array_push($dati,array("valore"=>"mamma", "etichetta"=>"mamma"));
         echo json_encode($dati);
}

or you can do 或者你可以做

public function test()
    {
     $dati = array();
             array_push($dati,array("valore"=>"ciao", "etichetta"=>"ciao"));
             array_push($dati,array("valore"=>"mamma", "etichetta"=>"mamma"));
             $this->output
    ->set_content_type('application/json')
    ->set_output(json_encode($dati));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM