2017-10-04 67 views
-4

我發送與JavaScript GET請求和解析的結果 var result = JSON.parse(response); 然後定義的變量「標題」 var title = result.title; 接着我試圖變量加載到與所述一個標籤編號=「fishplanet標題」 但HTML給了一個錯誤,說「標題」沒有定義。 document.getElementById("fishplanet-title").innerHTML = title; 我知道請求正在經歷,因爲我已將它記錄到控制檯。HTML不是在<script>標籤識別定義的變量

繼承人的要求: https://hastebin.com/eloqojimit.js

繼承人的響應: https://hastebin.com/vinadafelo.json

繼承人的錯誤: Uncaught ReferenceError: title is not defined at user.html:178

+2

請具體說明。發佈您的代碼:您如何提出請求,引發任何錯誤或拋出異常,以及您的「響應」實際上是什麼。如果您沒有提供足夠的信息,我們無法幫助您。 –

+0

請檢查[問]和[編輯](https://stackoverflow.com/posts/46573858/edit)您的問題,以包括一個[mcve]來演示問題。 – jmoerdyk

回答

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是一個數組,因此如果返回多於一個,則需要進行一些迭代。