我的函数工作正常,因为通过 AJAX 正确请求数据并根据需要显示数据,但也会引发以下错误:
TypeError: undefined is not an object (evaluating 'obj[i].title')
我的功能如下:
function populateNews(obj) {
var article = $('article p');
article.each(function(i) {
$(this).html('<p>'+obj[i].title+'</p>');
});
}
我不明白如何解决该错误。 populateNews(obj)
正在通过 .done()
从延迟的 AJAX 请求中调用;已阅读类似的帖子,暗示这可能是问题所在,但似乎没有答案适合我的特定情况。
最佳答案
不需要for
循环......错误只是意味着obj
的长度小于article
的长度>
function populateNews(obj) {
var article = $('article p');
//no need to have the for loop
article.each(function (i) {
//if obj[i] is not there update it with empty content
$(this).html('<p>' + (obj[i] ? obj[i].title : '') + '</p>');
});
}
关于javascript - AJAX请求导致 'undefined is not an object'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27014281/