2014-10-06 91 views
0

我使用jQuery的getJSON方法從JSON值... 以下是我爲代碼..從p​​hp文件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(); 
       }); 

     }); 

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

我是usin Freewall jQuery插件,我試圖從json數據動態地執行消息。 但是,如果我做"alert(data.data[i].title)"我得到所需output..but在"var id=data.data[i].id」,我得到錯誤data.data [i]是未定義...

請幫我解決這個問題..提前 感謝

回答

0

您的循環可能是問題。

for (i=0;i<paginationCount;i++) { 

如果在data.data數組中沒有20個項目會失敗,而不是安全的事情是

for (var i=0, len = data.data.length;i<len;i++) { 

您正在使用的循環計數器值靜態計數paginationCount,所以如果返回的結果不具有paginationCount項目數你的循環將嘗試訪問元素是出界也導致返回undefined

+0

感謝兄弟..它的工作......非常感謝您的幫助 – AbhiCool 2014-10-06 06:09:53