通过TVJS-tvOS调用API JSon

我正在尝试使用tvOS,并且在处理json调用方面有一些小问题。 我必须通过一个API获取一些数据,比方说为了testing,我打电话给这个链接

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,我该怎么做?

       

网上收集的解决方案 "通过TVJS-tvOS调用API JSon"

这是我工作的一个。 这在许多方面都不理想,但向您展示了一些开始。

 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, ' ')); } }); 

希望这可以帮助。

我在tvOS上testing了这一个,就像jQuery的语法(基本testing通过)一样:

 var $ = {}; $.ajax = function(options) { var url = options.url; var type = options.type || 'GET'; var headers = options.headers || {} ; var body = options.data || null; var timeout = options.timeout || null; var success = options.success || function(err, data) { console.log("options.success was missing for this request"); }; var contentType = options.contentType || 'application/json'; var error = options.error || function(err, data) { console.log("options.error was missing for this request"); }; if (!url) { throw 'loadURL requires a url argument'; } var xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.timeout = timeout; xhr.onreadystatechange = function() { try { if (xhr.readyState === 4) { if (xhr.status === 200) { if (xhr.responseType === 'json') { success(null, xhr.response); } else { success(null, JSON.parse(xhr.responseText)); } } else { success(new Error("Error [" + xhr.status + "] making http request: " + url)); } } } catch (err) { console.error('Aborting request ' + url + '. Error: ' + err); xhr.abort(); error(new Error("Error making request to: " + url + " error: " + err)); } }; xhr.open(type, url, true); xhr.setRequestHeader("Content-Type", contentType); xhr.setRequestHeader("Accept", 'application/json, text/javascript, */*'); Object.keys(headers).forEach(function(key) { xhr.setRequestHeader(key, headers[key]); }); if(!body) { xhr.send(); } else { xhr.send(body); } return xhr; } 

在Apple TV上工作的示例查询:

 var testPut = function(){ $.ajax({ type: 'PUT', url: url, success: successFunc, error: errFunc, dataType: 'json', contentType: 'application/json', data: data2 }); } var testGet = function(){ $.ajax({ dataType: 'json', url: url, success: successFunc, error: errFunc, timeout: 2000 }); } var getLarge = function(){ $.ajax({ dataType: 'json', url: url, success: successFunc, error: errFunc, timeout: 2000 }); } 

你有没有在“App.onLaunch”中调用你的函数

 App.onLaunch = function(options) { var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json'; var doc = getDocument(url); console.log(doc); } 

可能值得看看https://mathiasbynens.be/notes/xhr-responsetype-json

我碰到这个问题,想要完成同样的事情,并受@JasonJerrett的答案启发,但发现它有点缺乏,因为在我的例子中,我正在使用这样的Javascript中构build的XML模板:

 // Index.xml.js var Template = function() { return `very long xml string`; }; 

问题是你不能在模板本身内部执行XHR请求,因为模板string将在XHR请求实际完成之前返回(没有办法从asynchronouscallback中返回数据)。 我的解决scheme是修改资源加载器并在那里执行XHR请求,然后调用模板并将数据传递给模板函数:

 ResourceLoader.prototype.loadResource = function(resource, dataEndpoint, callback) { var self = this; evaluateScripts([resource], function(success) { if (success) { // Here's the magic. Perform the API call and once it's complete, // call template constructor and pass in API data self.getJSON(dataEndpoint, function(data) { var resource = Template.call(self, data); callback.call(self, resource); }); } else { var title = "Failed to load resources", description = `There was an error attempting to load the resource. \n\n Please try again later.`, alert = createAlert(title, description); Presenter.removeLoadingIndicator(); navigationDocument.presentModal(alert); } }); } // From: https://mathiasbynens.be/notes/xhr-responsetype-json ResourceLoader.prototype.getJSON = function(url, successHandler, errorHandler) { var xhr = new XMLHttpRequest(); xhr.open('get', url, true); xhr.onreadystatechange = function() { var status; var data; if (xhr.readyState == 4) { status = xhr.status; if (status == 200) { data = JSON.parse(xhr.responseText); successHandler && successHandler(data); } else { errorHandler && errorHandler(status); } } }; xhr.send(); }; 

然后需要修改模板函数以接受传入的API数据作为参数:

 // Index.xml.js var Template = function(data) { return 'really long xml string with injected ${data}'; }; 

您需要在XHR对象上实现onreadystatechange事件来处理响应:

 templateXHR.onreadystatechange = function() { var status; var data; if (templateXHR.readyState == 4) { //request finished and response is ready status = templateXHR.status; if (status == 200) { data = JSON.parse(templateXHR.responseText); // pass the data to a handler } else { // handle the error } } }; 

如果您想在应用程序启动时调用请求,只需添加application.js:

 App.onLaunch = function(options) { var javascriptFiles = [ `${options.BASEURL}js/resourceLoader.js`, `${options.BASEURL}js/presenter.js` ]; evaluateScripts(javascriptFiles, function(success) { if(success) { resourceLoader = new ResourceLoader(options.BASEURL); var index = resourceLoader.loadResource(`${options.BASEURL}templates/weatherTemplate.xml.js`, function(resource) { var doc = Presenter.makeDocument(resource); doc.addEventListener("select", Presenter.load.bind(Presenter)); doc.addEventListener('load', Presenter.request); navigationDocument.pushDocument(doc); }); } else { var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files."); navigationDocument.presentModal(errorDoc); } 

}); }

在presenter.js中添加一个方法:

 request: function() { var xmlhttp = new XMLHttpRequest() , method = 'GET' , url = 'your Api url'; xmlhttp.open( method , url , true ); xmlhttp.onreadystatechange = function () { var status; var data; if (xmlhttp.readyState == 4) { status = xmlhttp.status; if (status == 200) { data = JSON.parse(xmlhttp.responseText); console.log(data); } else { var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files."); navigationDocument.presentModal(errorDoc); } } }; xmlhttp.send(); },