代码之家  ›  专栏  ›  技术社区  ›  Austin Jones

未捕获的类型错误:无法读取未定义的属性“resource”

  •  2
  • Austin Jones  · 技术社区  · 6 年前

    我正在尝试使用查询从Craigslist中检索最后4个结果。我可以从结果中检索除图像的URL之外的所有信息,相反,它加载一个图像并吐出未捕获的类型错误:无法读取未定义的属性“resource”。对此,任何帮助都非常感谢。 这是检索项目的图像URL的行: data.query.results.item[i].enclosure.resource

    function getRSSFeed(feed){
    	// Build the YQL query
    	var qryRSS = 'select * from rss where url='+'"'+feed+'"';
    	// Initiate the YQL query
    	$.getJSON("http://query.yahooapis.com/v1/public/yql",
    	  {
    	    // settings API call
    	    q: qryRSS,
    	    format: "json"
    	  },
    	  function(data) {
    	    for (i=0; i<4; i++)
    	      {
    	      // Output a link, using the link attribute and the title attribute
    	      $('body').append('<a href="'+data.query.results.item[i].link+'">'+data.query.results.item[i].title+'<img src="'+data.query.results.item[i].enclosure.resource+'"></a>');
    	      // Output the description, using the description attribute.
    	      $('body').append(data.query.results.item[i].description);
    	    }
    	});
      };
      getRSSFeed('https://swmi.craigslist.org/search/sss?format=rss&query=grand%20prix');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    1 回复  |  直到 6 年前
        1
  •  2
  •   Luis Antonio Pestana    6 年前

    我建议您创建一个函数,并验证是否未定义附件。以下是完整的示例:

    <html>
      <head>
      </head>
      <body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script>
          function getRSSFeed(feed){
            // Build the YQL query
            var qryRSS = 'select * from rss where url='+'"'+feed+'"';
            // Initiate the YQL query
            $.getJSON("http://query.yahooapis.com/v1/public/yql",
              {
                // settings API call
                q: qryRSS,
                format: "json"
              },
              function(data) {
                for (i=0; i<4; i++)
                  {
                  // Output a link, using the link attribute and the title attribute
                  $('body').append('<a href="'+data.query.results.item[i].link+'">'+data.query.results.item[i].title+mountImg(data.query.results.item[i].enclosure)+'</a>');
                  // Output the description, using the description attribute.
                  $('body').append(data.query.results.item[i].description);
                }
            });
            };
    
            function mountImg(enclosure){
              if(typeof enclosure !== 'undefined')
                return '<img src="'+enclosure.resource+'" />';
            }
            getRSSFeed('https://swmi.craigslist.org/search/sss?format=rss&query=grand%20prix');    
        </script>
      </body>
    </html>