控制器
public function ajaxData(){
$country_id=$this->input->post('country_id',true);
$this->load->model('country_m');
$data['states']=$this->country_m->getStates($country_id);
echo json_encode($data);
$this->load->view('onlineappointment.tpl',$data,TRUE);
}
AJAX
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
// alert(countryID);
if(countryID){
$.ajax({
type:'POST',
url:'http://localhost/new_jivaamri/index.php/OnlineAppointment123/ajaxData',
data:'country_id='+countryID,
success:function(html){
console.log(html);
console.log(typeof html);
var obj2 = JSON.parse(html);
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
$('#address').html('<option value="">Select state first</option>');
}
});
我正在获取ajax响应的输出,如
{"states":[{"state_id":"45","state_name":" Kabul","country_id":"1","active":"1"},{"state_id":"46","state_name":"Kandahar","country_id":"1","active":"1"},{"state_id":"47","state_name":"Herat","country_id":"1","active":"1"},{"state_id":"48","state_name":"Mazar-i-Sharif","country_id":"1","active":"1"},{"state_id":"49","state_name":"Kunduz","country_id":"1","active":"1"},{"state_id":"50","state_name":"Taloqan","country_id":"1","active":"1"},{"state_id":"51","state_name":"Jalalabad","country_id":"1","active":"1"},{"state_id":"52","state_name":"Puli Khumri","country_id":"1","active":"1"}]}
但是如何检索州名
答案 0 :(得分:1)
解析回复:
JSON.parse()
然后获取州名:
parsed.states[index].state_name
编辑:如何在选项中显示选项。
<强> HTML 强>:
<select id="state_select"></select>
<强> JAVASCRIPT 强>
var option = '';
for (var i = parsed.states.length - 1; i >= 0; i--) {
options += "<option value=\""+parsed.states[i].state_name+"\">"+parsed.states[i].state_name+"</option>";
}
document.getElementById('state_select').innerHTML = options;
工作演示
var json = '{"states":[{"state_id":"45","state_name":" Kabul","country_id":"1","active":"1"},{"state_id":"46","state_name":"Kandahar","country_id":"1","active":"1"},{"state_id":"47","state_name":"Herat","country_id":"1","active":"1"},{"state_id":"48","state_name":"Mazar-i-Sharif","country_id":"1","active":"1"},{"state_id":"49","state_name":"Kunduz","country_id":"1","active":"1"},{"state_id":"50","state_name":"Taloqan","country_id":"1","active":"1"},{"state_id":"51","state_name":"Jalalabad","country_id":"1","active":"1"},{"state_id":"52","state_name":"Puli Khumri","country_id":"1","active":"1"}]}';
var parsed = JSON.parse(json);
var options = '';
for (var i = parsed.states.length - 1; i >= 0; i--) {
options += "<option value=\""+parsed.states[i].state_name+"\">"+parsed.states[i].state_name+"</option>";
}
document.getElementById('state_select').innerHTML = options;
&#13;
<select id="state_select"></select>
&#13;