2015-04-16 95 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变量设置为一个字符串并追加它。