AJAX 请求导致“未定义不是对象”错误

AJAX request results in 'undefined is not an object' error

本文关键字:对象 错误 未定义 请求 AJAX      更新时间:2023-09-26

我的函数工作正常,因为数据通过 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>');
    });
}