简体   繁体   English

本机javascript rest api调用

[英]native javascript rest api call

I am trying to make api call to get spotify albums in native javascript without using any js frameworks. 我正在尝试进行api调用,以在不使用任何js框架的情况下使用本机javascript获取Spotify专辑。 I am running into issues where I am unable to send Oauth token using native js. 我遇到无法使用本机js发送Oauth令牌的问题。 For spotify I have client id and client scret. 对于Spotify,我有客户端ID和客户端代码。 I can either use that or the Oa 我可以使用它或Oa

(function() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://api.spotify.com/v1/albums", false);
    xhr.send();
    document.getElementById("results").innerHTML = xhr.responseText;
})();
function request(callback) {

  var xobj = new XMLHttpRequest();
                 // true parameter denotes asynchronous
  xobj.open('GET', YOUR_URL_HERE, true);
  xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          // This marks that the response has been successfully retrieved from the server
          // Utilize callback
          callback(xobj.responseText);
        }
  };
  xobj.send(null);
}

I would definitely recommend taking a look at the link Frobber provided. 我绝对建议您看看Frobber提供的链接。 It's always better to understand why something does/doesn't work rather than just getting it to work. 总是总要了解为什么某事不起作用,而不是仅仅使它起作用。 Here is a mock request to get you started. 这是一个模拟请求,可帮助您入门。 Hope this helps! 希望这可以帮助!

I think you need to read a basic tutorial on how to use XMLHttpRequest, which you can find here 我认为您需要阅读有关如何使用XMLHttpRequest的基本教程,您可以在这里找到

One immediate problem with your code is that it's not using any callback to read the result that comes back from the server. 代码的一个直接问题是它没有使用任何回调来读取从服务器返回的结果。 This is all happening asynchronously, so what's occurring in your case is that you're send() ing the request, and then immediately setting innerHTML to a value that probably isn't even available from the server yet. 所有这些都是异步发生的,因此在您的情况下,您正在send()请求,然后立即将innerHTML设置为服务器可能还不可用的值。

Check the tutorial for how to get that information back from the server when it's ready. 查看教程,了解如何在服务器准备就绪时从服务器取回该信息。

Note the use of the myFunction callback, and note the use of onreadystatechange . 注意使用myFunction回调,并注意使用onreadystatechange What's happening here is that send() is sending something to the server, in a separate execution thread. 这里发生的是send()在单独的执行线程中向服务器发送内容。 You need to register a callback function that will perform the data fetching and DOM update when the server reports back that the data is available, not immediately. 您需要注册一个回调函数,当服务器报告该数据可用时( 而不是立即),该回调函数将执行数据获取和DOM更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM