consuming API JSon calls through TVJS-tvOS

前端 未结 6 720
终归单人心
终归单人心 2021-02-06 10:32

I am trying to play with tvOS, and I have small question regarding handling json call. I have to get some data through an API, let\'s say for sake of test that I am calling this

6条回答
  •  -上瘾入骨i
    2021-02-06 11:00

    This is one that I got working. It's not ideal in many respects, but shows you something to get started with.

    function jsonRequest(options) {
    
      var url = options.url;
      var method = options.method || 'GET';
      var headers = options.headers || {} ;
      var body = options.body || '';
      var callback = options.callback || function(err, data) {
        console.error("options.callback was missing for this request");
      };
    
      if (!url) {
        throw 'loadURL requires a url argument';
      }
    
      var xhr = new XMLHttpRequest();
      xhr.responseType = 'json';
      xhr.onreadystatechange = function() {
        try {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              callback(null, JSON.parse(xhr.responseText));
            } else {
              callback(new Error("Error [" + xhr.status + "] making http request: " + url));
            }
          }
        } catch (err) {
          console.error('Aborting request ' + url + '. Error: ' + err);
          xhr.abort();
          callback(new Error("Error making request to: " + url + " error: " + err));
        }
      };
    
      xhr.open(method, url, true);
    
      Object.keys(headers).forEach(function(key) {
        xhr.setRequestHeader(key, headers[key]);
      });
    
      xhr.send();
    
      return xhr;
    }
    

    And you can call it with the following example:

    jsonRequest({
      url: 'https://api.github.com/users/staxmanade/repos',
      callback: function(err, data) {
        console.log(JSON.stringify(data[0], null, ' '));
      }
    });
    

    Hope this helps.

提交回复
热议问题