2012-11-27 134 views
0

我想使用Json在我的代碼點火器視圖上查看數據。它返回在選擇選項數組中的回聲json數據

[{「id」:「5」,「cityname」:「Manegerial Estate」},{「id」:「6」,「cityname」:「Kilimani」},{「id」 12「,」cityname「:」Artisan「}]

部分代碼。我如何在選項選擇中回顯返回的線索。與之呼應的選擇返回值如上

var post_url = "control_form/get_cities_by_state/"+ state_id; 
     $.ajax({ 
      url: post_url, 
      type: "POST", 

      // dataType: 'json', 
      success: function(cities) //we're calling the response json array 'cities' 
       { 
       alert(cities); 
       $('#f_city').empty(); 
       $('#f_city, #f_city_label').show(); 
        $.each(cities,function(id,city) 
        { 
        var items=cities['id']; 
        alert(items); 
        var opt = $('<option />'); // here we're creating a new select option for each group 
         opt.val(id); 
         opt.text(city); 
         $('#f_city').append(opt); 
        }); 
      }); //end AJAX 
     } else { 
     $('#f_city').empty(); 
     $('#f_city, #f_city_label').hide(); 
    }//end if 
}); //end change 
}); 
    </script> 
</head> 
<body> 
    <p> 
<?php echo form_open('control_form/add_all'); ?> 
     <label for="f_state">State<span class="red">*</span></label> 




     <select id="f_state" name="f_state" required> 
      <option value="" selected=selected>--Select state--</option> 
      <?php 
      foreach($statename as $state): 
       echo '<option value="' . $state->id . '">' . $state->statename . '</option>'; 
      endforeach; 
      ?> 

     </select> 
     <label for="f_city" id="f_city_label">City<span class="red" >*</span></label> 
     <!--this will be filled based on the tree selection above--> 
     <select id="f_city" name="f_city" id="f_city_label"> 
      <option value=""></option> 
     </select> 
     <label for="f_membername">Member Name<span class="red">*</span></label> 
     <input type="text" name="f_membername"/> 
<?php echo form_close(); ?> 


    </p> 
</body> 
</html> 

回答

0

你需要指定JSON的dataType ...

$.ajax({ 
     url: post_url, 
     type: "POST", 
     dataType: "json", 

然後在你的成功的功能:

$.each(cities,function(i, city) { 

    var opt = $('<option />'); // here we're creating a new select option for each group 
    opt.val(city.id); 
    opt.text(city.cityname); 
    $('#f_city').append(opt); 

}); 
+0

我已經更新了代碼,它仍然不起作用,如果我使用json數據類型,它返回對象對象 –

+0

嘗試更新的版本。我在jsfiddle中運行它,它按預期工作。 http://jsfiddle.net/HSxmC/ - 我解析了json字符串來測試。它應該爲你工作。 –

+0

謝謝你,工作 –