2016-03-15 67 views
0

我能夠從從控制器JSON格式的數據庫成功地獲取數據,這是它的外觀:填充下拉與JSON數據jQuery和AJAX

{ 
    "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>'); 
          } 
         }); 

回答

1

你的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"}, {...}]} 

這些可以在您的$.eachval.idval.name

+0

仍然沒有得到任何東西到下拉:( – Himanshu

+0

@Himanshu - 做你的JSON改變我怎麼顯示? – ImClarky

+0

它工作感謝人:)你救了我的生命...以前我改變了我的視圖代碼現在它的工作完美:) – Himanshu

0

Fiddle

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