javascript - 通过 TVJS-tvOS 使用 API JSon 调用

标签 javascript node.js xcode api tvos

我正在尝试使用 tvOS,但我有一个关于处理 json 调用的小问题。我必须通过 API 获取一些数据,假设为了测试我正在调用此链接

http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json

我尝试通过一些修改来使用这个函数

function getDocument(url) {
  var templateXHR = new XMLHttpRequest();
  templateXHR.responseType = "json";
  templateXHR.open("GET", url, true);
  templateXHR.send();
  return templateXHR;
}

但没有成功。任何提示或帮助?

如果我需要使用 NodeJS,我该怎么做?

最佳答案

这是我开始工作的。它在许多方面并不理想,但向您展示了一些入门知识。

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;
}

你可以用下面的例子调用它:

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

希望这对您有所帮助。

关于javascript - 通过 TVJS-tvOS 使用 API JSon 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32553651/

相关文章:

javascript - 如何更换2 |无缘无故?

javascript - 如何使用 sinon 在回调中测试回调?

javascript - 无法使用 JavaScript 通过 Outlook 帐户登录 Azure AD v2 帐户

javascript - 如何检测元素的点击

javascript - Azure DevOps Rest API getWorkItems 不返回指定的字段

ios - 如何在 Xcode 8 上将状态栏设置为 "Light"(最好不要通过代码)

c++ - 命令行应用程序的自定义 URL 方案

javascript - 如何通过url传递特殊字符 '/'

javascript - Node JS : get number of files in a directory

ios - Xcode 4.4 - 无法运行项目