【问题标题】:Undefined is not a function (AJAX, PHP, jQuery)未定义不是函数(AJAX、PHP、jQuery)
【发布时间】:2015-04-16 01:57:50
【问题描述】:

我对@9​​87654321@ 和 AJAX 很陌生,所以如果我很愚蠢,我深表歉意。

我的 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()
{
	$.ajax({
	    type: "GET",
	    url: "/tutorials/retrieve",
	    dataType: "json",
	    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);
            
		},
		error: function() {
			alert("An error occurred while processing XML file.");
		}
	});
}

我目前收到的错误是“Uncaught TypeError: undefined is not a function”,它指的是以下部分

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

关于我哪里出错了有什么想法吗? 我之前使用过非常相似的代码,效果很好

【问题讨论】:

  • 这个var tutorial = ('')是什么意思?

标签: javascript php jquery ajax json


【解决方案1】:

试试这个

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

【讨论】:

  • 不幸的是问题仍然存在。
  • 你需要一些选择器,你能检查修改后的版本吗?
【解决方案2】:

您应该选择任何 DOM 元素并将其分配给教程变量,如下所示:

var tutorial = $('someCSSselector');

【讨论】:

    【解决方案3】:

    因为您在('') 上调用.append(),所以出现错误。 .append() 是一个 jQuery 函数,但 ('') 是一个空字符串,而不是一个 jQuery 对象。

    你可以这样做:

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

    【讨论】:

      【解决方案4】:

      你应该先定义你的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>'))
        });
      

      【讨论】:

      • 这修复了错误,但对我的需求无效,因为我必须为每次迭代生成一个框。此方法将所有内容放入一个生成的盒子中,而不是多个。以上答案更适合我的需求。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多