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

cannot get the results to be displayed on the page

本文关键字:显示 结果      更新时间:2023-09-26

我无法显示从数据库中获得的结果:

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

我从控制台得到这个错误:

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

请检查我的代码,找出我的错误。

这是我的观点:

<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>  

控制器:

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文件:

$("#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"));
            });   
        }
    });
   });  

您需要告诉jQuery从服务器返回的内容类型(json)

默认为'string',它没有理由认为这是不正确的。

请参阅文档以获取正确的参数顺序。您的.each迭代器正在尝试遍历字符串,并且-显然-失败。


编辑:作为一个迂腐的观点,你为什么使用POST来获取数据?

我认为应该是$.get$.getJSON快捷键,而不是$.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" );
});

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