使用 jquery 和 ajax 用 JSON 数据填充下拉列表


Populate dropdown with JSON data using jquery & ajax

我能够成功地从控制器以json格式从数据库中获取数据,如下所示:

{
    "dealer":[
        ["1","himanshu"],
        ["2","bhola the dealer"],
        ["3","bhola the dealer"]
    ]
}

问题是我无法将 json 数据从控制器传递到视图中的下拉列表中。

型号代码:

 public function getName(){
     $this->db->select('dealerid,dealername');
    $query=$this->db->get('Dealer');
    $result=$query->result_array();
    //echo "<pre>";
    return $result;
    }

控制器代码:

  public function dealer_list()
{
    $list = $this->person->getName();
    $ddata = array();
    foreach ($list as $person) {
        $row = array();
        $row[] = $person['dealerid'];
        $row[] = $person['dealername'];
        $ddata[] = $row;
    }
    $output = array(
        "dealer" => $ddata,
            );
    //output to json format

   echo json_encode($output);
}

查看代码:

                   //get a reference to the select element
                        $select = $('#select');
                        //request the JSON data and parse into the select element
                        $.ajax({
                            url: "<?php echo site_url('dealer_controller/dealer_list')?>"
                            , dataType: 'JSON'
                            , success: function (data) {
                                //clear the current content of the select
                                $select.html('');
                                //iterate over the data and append a select option
                                $.each(data.dealer, function (key, val) {
                                    $select.append('<option id="' + val.id + '">' + val.name + '</option>');
                                })
                            }
                            , error: function () { <strong>
                                //if there is an error append a 'none available' option
                                $select.html('<option id="-1">none available</option>');
                            }
                        });

您的 JSON 输出没有每个经销商的密钥idname。因此,val.idval.name不起作用。

在控制器更改中:

$row[] = $person['dealerid'];
$row[] = $person['dealername'];

自:

$row["id"] = $person['dealerid'];
$row["name"] = $person['dealername'];

这会将键idname添加到 php 数组中,当转换为 json 时,应输出如下内容:

{"dealer":[{"id": "1", "name": "himanshu"}, {...}]}

然后可以使用val.idval.name在您的$.each中检索这些

小提琴

 $.each(data.dealer, function (index, item) {
        $select.append(
            $('<option>', {
                value: item[0],
                text: item[1]
            }, '</option>'))
          }
         )
    })