【问题标题】:Pull data from Bandsintown API从 Bandsintown API 中提取数据
【发布时间】:2020-08-27 07:04:30
【问题描述】:

我需要一些帮助来从 Bandsintown API 中提取事件数据。我在 Postman App 中测试了 HTTP GET 请求,它正确返回了数据。

现在我正在尝试将这些数据提取到 JavaScript 中,然后将其呈现在我设计的网站上,但似乎有些东西不起作用。这是我的代码:

var eventRequest = new XMLHttpRequest();
eventRequest.open('GET', 'https://rest.bandsintown.com/artists/${artistname}/events?date=upcoming&app_id=${app_id}');
eventRequest.onload = function() {
  var eventsData = eventRequest.responseText;
};
eventRequest.send();

在我正在使用的 JS 中进一步渲染数据:

document.getElementById("app").innerHTML = `
   ${eventsData.map(eventTemplate).join("")}
`;

【问题讨论】:

  • 很有可能,onload 中的 asynchronous 回调没有填充 eventsData ...而不是将代码“进一步向下”,将其放在 里面 onload 回调,其中数据可用 ...注意onload 回调中的var eventsData 除了在声明它的那个函数中之外,肯定不会在任何地方可用 - 那就是变量如何工作

标签: javascript arrays get


【解决方案1】:

你可以试试这个,在日志中可能会看到更多错误。

var eventRequest = new XMLHttpRequest();

eventRequest.open("GET", "https://rest.bandsintown.com/artists/${artistname}/events?date=upcoming&app_id=${app_id}", true);

eventRequest.onreadystatechange = function (event) {  
    if (eventRequest.readyState === 4) {  
        if (eventRequest.status === 200) {  
          console.log(eventRequest.responseText)  
        } else {  
           console.log("Error", eventRequest.statusText);  
        }  
    }  
}; 

eventRequest.send(null); 

【讨论】:

    【解决方案2】:

    另外,我很确定如果你想在你的 url (${artistname}) 中使用字符串文字,你需要反引号 (``) 而不是单引号或双引号。

    'https://rest.bandsintown.com/artists/${artistname}/events?date=upcoming&app_id=${app_id}'
    

    `https://rest.bandsintown.com/artists/${artistname}/events?date=upcoming&app_id=${app_id}`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-19
      • 2013-06-14
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2020-03-14
      相关资源
      最近更新 更多