Codeigniter: how to foreach in javascript with a returned array
I need to loop through a returned array in javascript but it doesn't work, it will loop through each letter of the word array instead of loopin开发者_StackOverflowg throught the value.
this is the javascript code
$.ajax({
url: "<?php echo site_url('home/getsubcats'); ?>",
type: 'POST',
data: form_data,
success: function(msg)
{
for ( var i in msg )
{
alert( msg[i] );
}
//$('#main_content').html(msg);
}
});
and this is the controller (it get's the correct data so the query is not the problem);
function getsubcats()
{
$this->load->model('site_model');
if ($this->input->post('ajax')):
$catid = $this->input->post('id');
return $this->site_model->getSubCats($catid);
endif;
}
You might have to add returnType: 'json'
to your $.ajax option object if your code returns JSON.
If your code loops over single characters it means msg
is a string and not an array.
Additionally, use for(var i = 0; i < msg.length; i++)
as for in
loops will also include inherited attributes - so when using javascript frameworks which extend Object.prototype or Array.prototype you might run into trouble.
You are most likely iterating on a string response, not an Array. I don't think jQuery makes the conversion automatically.
I'm not familiar with CodeIgniter, but when you return getSubCats(), is the result automatically encoded into JSON? Because if not, you must encode it before sending it to the client.
Use the net panel of Firebug or the Resources tab in Chrome to inspect the actual response.
精彩评论