我无法显示从数据库获得的结果:
{"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/