【问题标题】:Javascript JSON results throws text is null errorJavascript JSON 结果抛出 text is null 错误
【发布时间】:2013-07-25 00:56:46
【问题描述】:

我正在使用 ajax 从 instagram 中提取照片。下面是ajax调用:

$.ajax({
    type: "GET",
    dataType: "jsonp",
    cache: false,
    url: "https://api.instagram.com/v1/media/search?lat=" + lat +"&lng=" + lng + "&distance=" + distance + "&access_token=" + accessToken + "",
    success: function(data) {

        for (var i = 0; i < 6; i++) {
             $("#instagram").append("<li><a class='group' title='' href='" + data.data[i].images.standard_resolution.url +"'><img src='" + data.data[i].images.thumbnail.url +"' /></a>");   
        }     

    }
});

这很好,因为锚标题属性留空。我使用title='" + data.data[i].caption.text + "' 将instagram 标题作为锚标题。在大多数情况下,这是可行的,但我经常收到以下错误:“Uncaught TypeError: Cannot read property 'text' of null”

我假设这是由于以下两个原因之一: A)根本没有标题 B) 带有不能用作标题的字符的标题。

有谁知道为什么会这样,以及我该如何解决这个问题?我尝试了以下但它抛出了同样的错误:

if(data.data[i].caption.text != null) { 
     var title = data.data[i].caption.text;
} else {
     var title = "";
}

有什么想法吗?

【问题讨论】:

  • 这里的情况是:标题为空。 B 不会触发该错误。我猜响应不包括空字段以优化网络。在使用标题属性之前检查 null。
  • 当我正在检查时,我将如何在使用它之前检查 null...如果标题为 null?

标签: ajax json instagram


【解决方案1】:

如果没有附加标题,Instagram 不会返回该字段。只需添加另一个空检查。

if (data.data[i].caption !=null) {
    if(data.data[i].caption.text != null) { 
       var title = data.data[i].caption.text;
    } 
} else { 
   var title = "";
}

【讨论】:

  • 这很好用,谢谢。我不知道如果留空,Instagram 不会返回该字段。我以为它只会返回一个空字符串
【解决方案2】:
for (x in data.data) {
    var title_text = '';

    if (data.data[x].caption != null) {
        if (data.data[x].caption.text != null) {
            title_text = data.data[x].caption.text;
        }
    } else {
        title_text = "";
    }

    $("#instagram").append("<a target="_blank" href="' + data.data[x].link + '">" + title_text);
}

【讨论】:

    猜你喜欢
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 2020-07-21
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多