2015-04-16 147 views
0

我對jQuery和AJAX很新,所以我很抱歉如果我是愚蠢的。未定義不是函數(AJAX,PHP,jQuery)

我收到我的AJAX jQuery腳本中的錯誤。 我通過AJAX獲取數據在我的頁面上動態顯示。 JSON文件返回一個數組,它必須迭代並顯示在每個項目的DIV中。 的JSON是:

[{"id":1, "user_id":14, "title":"The Title", "thumbnail":"image.jpg", "summary":"summary of post", "content":"content info here", "category":"Graphic Design", "sub_category":"Adobe Photoshop", "views":0, "published":0, "created_at":"2015-04-16 00:09:57", "updated_at":"2015-04-16 00:09:57"}, {and so on...}]

jQuery是:

function retrieveTutorials() 
 
{ 
 
\t $.ajax({ 
 
\t  type: "GET", 
 
\t  url: "/tutorials/retrieve", 
 
\t  dataType: "json", 
 
\t  success: function(data){ 
 
      var tutorial = ('') 
 
      $.each(data, function(){ 
 
      
 
        tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>')) 
 
      }); 
 
      
 
      $("#generated-content").empty().append(tutorial); 
 
      
 
\t \t }, 
 
\t \t error: function() { 
 
\t \t \t alert("An error occurred while processing XML file."); 
 
\t \t } 
 
\t }); 
 
}

我目前收到的錯誤是 「遺漏的類型錯誤:未定義是不是一個函數」,它指到以下部分

tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))

任何想法,我要去的地方錯了嗎? 我已經使用了非常相似的代碼工作正常之前

+0

這個'var tutorial =('')'是什麼意思? –

回答

2

試試這個

var tutorial = $('<div></div>'); 
+0

不幸的是,問題仍然存在。 – Dale

+0

你需要一些選擇器,你可以檢查修改後的版本嗎? –

+0

謝謝,這項工作 – Dale

2

你應該選擇任何DOM元素並將其分配給補習變量,像這樣:

var tutorial = $('someCSSselector'); 
0

你應該首先定義你的div對象,並在定義它時保留generatedbox類。然後,您可以省略附加內容中的div

var tutorial = $('<div class="generatedbox">') 
    $.each(data, function(){    
     tutorial.append($('<img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p>')) 
    }); 
+0

這修復了錯誤,但是對我的需求沒有效果,因爲我必須爲每次迭代生成一個框。此方法將所有內容都放入單個生成的框中,而不是多個。以上答案對我的需求更好。 – Dale

1

由於您在('')上致電.append(),因此存在錯誤。 .append()是一個jQuery函數,但('')是一個空字符串,而不是一個jQuery對象。

你可以這樣做:

var tutorial = $('<div>'); 
... 
$("#generated-content").empty().append(tutorial.html()); 
0

怎麼這樣呢?

$.ajax({ 
     type: "GET", 
     url: "/tutorials/retrieve", 
     dataType: "json", 
     success: function(data){ 
      var tutorial = ''; 
      $.each(data, function(){ 
       tutorial += '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'; 
      }); 

      $("#generated-content").empty().append(tutorial); 

     }, 
     error: function() { 
      alert("An error occurred while processing XML file."); 
     } 
    }); 

基本上,您將tutorial變量設置爲一個字符串並追加它。