无法获得要在页面上显示的结果

I cannot display the results which I got from database:

{"results": ["USA", "Canada"]} 
{"message":"Could not find any countries."} //else

I got this error from console:

Uncaught TypeError: Cannot read property 'length' of undefined.

Could you please check my code to find out what is my mistake.

Here is my view:

<a href="#my_div" id="load_country_list">My Travel Plans</a> 
<div id="my_div">             
<div id="country_list_is_got"></div>
<div id="country_list_is_not_got"></div>
</div>  

Controller:

if ($this->my_model->did_get_country_list($user_id)) {              
$country["results"]= $this->model_users->did_get_country_list($user_id);            
       echo json_encode($country);          
        }
        else {      
        $country = array('message' => "Could not find any countries." );
            echo json_encode($country);     
        }

JS file:

$("#load_country_list").click(function() { 

    $.post('cont/get_country_list', function (country) {
        if (country.message !== undefined) {
            $( "#country_list_is_not_got").text(country.message);
        } else {
            $.each(country.results, function(i, res) {
                 var item = $('<div>'),               
                     title = $('<h3>');
                     title.text(res);
                     item.append(title);
                     item.appendTo($("#country_list_is_got"));
            });   
        }
    });
   });  

You need to tell jQuery what content type is coming back from the server (json)

It defaults to 'string' and it has no reason to think that's incorrect.

See the documentation for the correct parameter order. Your .each iterator is trying to loop over a string, and - obviously - failing.


Edit: As a point of pedantry, why are you using POST to GET data? "Get" is literally in your URL.

Live Demotry this, issue is results contain array.but you try to use key,value

   if (country.message !== undefined) {
        $( "#country_list_is_not_got").text(country.message);
    } else {
        for(i=0;i<country.results.length;i++){
                 var item = $('<div>'),               
                 title = $('<h3>');
                 title.text(country.results[i]);
                 item.append(title);
                 item.appendTo($("#country_list_is_got"));

        }  
    }

I think it should be $.get or the $.getJSON shortcut, instead of $.post

$.getJSON("cont/get_country_list", function( data ) {
  console.log(data);

  // something like this for list construction and append to body
  var countries = [];

  // maybe you need data.results here, give it a try or see console
  $.each( data, function( key, val ) {
    countries.push( "<li id='" + key + "'>" + val + "</li>" );
  });

  $( "<ul/>", {
    "class": "country-list",
    html: countries.join( "" )
  }).appendTo( "body" );
});