2016-04-03 10 views
0

我想在我的項目中實現無限滾動。我創建了3頁index.php,ajax.php和script.js。索引工作正常。 Ajax.php從mysql數據庫以json格式返回數據。使用Ajax加載json數據(未捕獲TypeError:無法讀取未定義的屬性'長度')

問題與script.js 以下是代碼。

的script.js:

$(window).scroll(function() { 
if($(window).scrollTop() + $(window).height() == $(document).height()){ 
     first = $('#first').val(); 
     limit = $('#limit').val(); 
     no_data = true; 
     if(flag && no_data){ 
      flag = false; 
      $('#loader').show(); 

      $.ajax({ 
       url : 'ajax.php', 
       dataType: "json", 
       type: 'post', 
       data: { 
        start : first, 
        limit : limit 
       }, 
       success: function(data) { 
        flag = true; 
        $('#loader').hide(); 

        if(data.count > 0){ 
         first = parseInt($('#first').val()); 
         limit = parseInt($('#limit').val()); 
         $('#first').val(first+limit); 
         $("#jc").append("<p>Test</p>"); 
         //$('#jc').append(); 
         $.each(data.content, function(key, value){ 
          alert(value.name); 
          //$("#jc").append("<p>Test1</p>"); 
          html +=value.name; 
          html += '<span class="month"><i class="fa fa-calendar"></i>'+value.name+'</span><p>&nbsp;</p>'; 
          html += '<p><a href="'+value.email+'" target="_blank">Demo </a></p>'; 
          html += '<p><a href="'+value.job_description+'" target="_blank">Tutorial </a></p>'; 


          html += '<p>'+value.mobile+'</p>'; 
          html += '</li>'; 
          $('#jc').append(html); 


         }); 

        }else{ 
         alert('No more data to show'); 
         no_data = false; 
        } 
       }, 
       error: function(data){ 
        flag = true; 
        $('#loader').hide(); 
        no_data = false; 
        alert('Something went wrong, Please contact admin'); 
       } 
      }); 
     } 


    } 
}); 

好像

`$.each(data.content, function(key, value){` 

問題與此線,因爲這樣我把警告標籤之後,但不點火。

JSON數據

{"count":2,"0":{"name":" Admin","email":"[email protected]","description":"We are looking json data. ","mobile":"123456789","newDate":"01-Apr-2016"},"1":{"name":"Raja","email":"[email protected]","description":"testing testing ","mobile":"43455435422","newDate":"31-Mar-2016"}} 

我在控制檯檢查,發現這個錯誤。 jquery-2.1.3.min.js:2 Uncaught TypeError: Cannot read property 'length' of undefined

回答

2

首先,在您的提醒之前的$.each(),您應該迭代data而不是data.content。存儲在data中的對象沒有content屬性。

然後,在你data對象,第一個鍵/值對爲"count":2,因此您的警報正在努力讀書的2name財產。只有在其他鍵/值對中,您的值纔是具有name屬性的對象。

你可以嘗試檢查,如果該值有name財產試圖調用之前:

$.each(data, function(key, value){ 
    if (value.name) { 
     alert(value.name); 
    } 

    // etc. 
+0

謝謝您的回答。註冊了 – Ironic

+0

我們也可以使用hasOwnProperty,'value.hasOwnProperty('name')'來檢查它。 – sahil

+0

它的工作,但我得到一個額外的JSON數據爲未定義。像json從數據庫中返回2條記錄,但是當我將它們打印爲html時,我得到了額外的記錄(udefined)。 – Ironic

相關問題