我正在使用jQuery getJson方法从json获取值... 以下是我的代码..
//var data_url="message.json";
var data_url="php/server_processing.php";
var count = 0;//will be computed(no of entries in json file)
var paginationCount=20;
var i=0,j=0;
var symflag=0;
$(window).load(function () {
$.getJSON(data_url, function(data) {
for(var key in data.data) {
if(data.data.hasOwnProperty(key)) {
count++;
}
}
//alert("count:"+count);
var output="";
//alert(data.data[0].short_desc);
for (i=0;i<paginationCount;i++) {
//alert(data.data[i].title);
var id=data.data[i].id;
var title=data.data[i].title;
var short_desc=data.data[i].short_desc;
var created_by=data.data[i].created_by;
var date=data.data[i].date;
var time=data.data[i].time;
output+="<div class='brick'><div class=mhead>"
+ id + " "
+ title + "</div><div class='mbody'>"
+ short_desc + "</div><div class='mfoot'>"
+ created_by+ " "
+ date+ " "
+ time+"<a data-toggle='modal' data-target='#myModal' onclick='fillmodaldata(" +i+")'> more...</a></div></div>";
}
$( "#freewall" ).append( output );
wall.fitWidth();
});
});
从php文件输入json:
{"data":[
{"id":1,"category":"Computer programming","title":"C","short_desc":"C","created_by":"ash","date":"03\/07\/2014","time":9},
{"id":2,"category":"Web","title":"D","short_desc":"asdasdasd","created_by":"mad","date":"03\/07\/2014","time":1},{"id":3,"category":"UI","title":"B","short_desc":"dfvdfvfdv","created_by":"ron","date":"03\/07\/2014","time":2}]}
我在Freewall jQuery插件中使用,我正在尝试从json数据动态执行消息。
但是,如果我"alert(data.data[i].title)"
我得到了所需的输出..但在"var id=data.data[i].id
“,我收到错误data.data [i]未定义...
请帮我解决这个问题.. 提前致谢
答案 0 :(得分:0)
你的for循环可能是问题。
for (i=0;i<paginationCount;i++) {
如果data.data数组中没有20个项目,它将失败,而安全的事情是
for (var i=0, len = data.data.length;i<len;i++) {
您使用静态计数paginationCount
作为循环计数器值,因此如果返回的结果没有paginationCount
个项目,您的循环将尝试访问超出范围的元素它导致返回undefined