无法获得要在页面上显示的结果
cannot get the results to be displayed on the page
我无法显示从数据库中获得的结果:
{"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"));
}
}
相关文章:
- 当查询不在displayField中时,引导Ajax Typeahead不显示结果
- JavaScript循环无法正确计算/显示结果
- 将循环中的两个文本框相乘,并在第三个文本框上显示结果
- BMI计算器以Javascript显示结果
- 在表中显示结果
- onchange选择get value并执行查询,然后在同一页面上显示结果
- 搜索XML文件并使用javascript显示结果
- Moment.js不显示结果
- 使用jQuery延迟表单输入,并在延迟后在同一页面上显示结果
- 防止 PHP 在新页面中显示结果
- jquery jqgrid 不显示结果,具体取决于 JSON 对象中的参数
- Angular-如何显示结果,仅在未选中时显示
- backbone.js视图没有't由于异步获取而显示结果;t渲染
- jqueryajax帖子将我发送到操作页面,并且不会显示结果数据
- 添加两个数字,并使用Javascript在文本框中显示结果
- 接受用户输入,与JSON数据匹配,并以javascript显示结果
- 自动完成 JQuery 不显示结果
- 控制台.log或显示结果的函数
- 提交表单,使用脚本处理信息,并在同一页面上显示结果
- AJAX 实时搜索仅当结果以相同的第一个字母开头时才显示结果