javascript – 通过TVJS-tvOS消费API JSon调用
发布时间:2020-12-14 19:45:12 所属栏目:百科 来源:网络整理
导读:我正在尝试使用tvOS,我对处理json调用有一个小问题.我必须通过API获取一些数据,让我们说为了测试我正在调用此链接 http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22format=json 我尝试
我正在尝试使用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,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,' ')); } }); 希望这可以帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |