HTML无法识别<script>标记中的已定义变量

时间:2017-10-04 20:44:38

标签: javascript jquery html

我发送了一个带有javascript的GET请求并解析了结果&#xA; var result = JSON.parse(response); &#xA;然后定义变量“title”&#xA; var title = result.title; &#xA;接下来我尝试将变量加载到id =“fishplanet-title”&#xA的标记中;但是HTML给出了一个错误,说“标题”没有定义。&#xA; document.getElementById(“fishplanet-title”)。innerHTML = title; &#xA;我知道请求正在通过,因为我已将其登录到控制台。

&#xA;&#xA;

继承人请求:&#xA; https://hastebin.com/eloqojimit.js

&#xA;&#xA ;

继承人的回应:&#xA; https://hastebin.com/vinadafelo.json

&#xA;&#xA;

继承错误:&#xA; 未捕获的ReferenceError:标题未定义&#xA; at user.html:178

&#xA;

1 个答案:

答案 0 :(得分:1)

result.title无效。 title属性位于数组中,因此您需要对其进行迭代以获取title值:

{
    "appnews": {
        "appid": 380600,
        "newsitems": [
            {
                "gid": "2175660043472720797",
                "title": "QuestionsAnswers",
                "url": "http://store.steampowered.com/news/externalpost/steam_community_announcements/2175660043472720797",
                "is_external_url": true,
                "author": "Olcha",
                "contents": "1.\"What is the garage icon for at the bottom of the Inventory page? Will this be for boat access and when can we expect boats to be launched?\" That’s right - the Garage will soon be the place from where you can access Boats. That’s exactly what we are currently working hard on and we plan to release this feature in the nearest future. Actually, we’ll share a video with you guys next week! Make sure to keep track of our news - it’ll be fun! 2. \"Will we see traditional carp fishing features such a...",
                "feedlabel": "Community Announcements",
                "date": 1506799022,
                "feedname": "steam_community_announcements",
                "feed_type": 1,
                "appid": 380600
            }
        ]
        ,
        "count": 277
    }
}

要访问title属性,您需要执行以下操作:

var title = JSON.parse(result).appnews.newsitems[0].title;

由于newsitems是一个数组,如果返回多个数组,则需要进行一些迭代。