javascript - 无法获取页面显示的结果

标签 javascript php jquery ajax json

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

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

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

$("#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”,并且没有理由认为这是不正确的。

参见the documentation以获得正确的参数顺序。 您的 .each 迭代器正在尝试循环遍历字符串,但显然失败了。

<小时/>

编辑:作为一个迂腐的观点,你为什么使用 POST 来获取数据? “获取”实际上就在您的网址中。

关于javascript - 无法获取页面显示的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25145020/

相关文章:

javascript - Bootstrap.js Carousel 加载特定元素

javascript - Jquery帮助处理鼠标事件,事件未解除绑定(bind)

javascript - HTML 不显示已解码的 %3C?

javascript - 如何检测窗口哈希的变化?

php - wkhtmltopdf:是否可以合并 PDF 文件?

php - 如何通过codeigniter在mysql中插入多选下拉值( View -> Controller ->模型)

jquery - 制作具有固定标题和固定侧边栏的可滚动表格

javascript - MSXML : Javascript is not a scripting language

php - Doctrine 不存储 ArrayCollection

javascript - 在javascript中获取超链接的值