如何在TVML应用程序中使用AJAX请求?

时间:2016-05-09 18:52:16

标签: ios ajax tvos tvml

我的浏览器中有一个有效的AJAX请求。现在我需要在TVML项目中使用GET请求来获取我的JSON数据。怎么做更好?

我正在尝试使用XMLHttpRequest,但它不起作用或者我做错了什么?

function performRequest(type, route, data) {
        return $.ajax({
            type: type,
            dataType: 'json',
            url: url + route,
            data: data
        });
    }

    function getChannels() {
        log(' > get channels');
        return performRequest('GET', 'channel/list', {
            id: browserId
        }).then(function (response) {
            response.data.forEach(function (channel) {
                channels[channel.id] = channel;
            });
        });
    }

2 个答案:

答案 0 :(得分:0)

在我看来,您的代码使用的是jquery,而不是XMLHTTPRequest。就个人而言,我没有成功地使用TVJS运行jquery,因为它对TVJS不满足的Document类做出了一些假设。我没有详细分析这个问题,也许你可以找到一些解决方法。

如果要使用原生XMLHTTPRequest下载JSON资源,请尝试以下操作:

/**
 * Downloads a JSON resource
 *
 * @param {Object}      options                 The options parameter.
 * @param {string}      options.resourcePath    Path to the JSON
 * @param {Function}    options.success         On success, will be called with the resulting JSON object
 * @param {Function}    [options.error]         Error callback
 */
getJSON(options) {

    var resourceXHR = new XMLHttpRequest();
    resourceXHR.responseType = "json";
    resourceXHR.addEventListener("load", (function () {
        options.success(resourceXHR.response);
    }));
    resourceXHR.addEventListener("error", (function () {
        options.error({status: resourceXHR.status, statusText: resourceXHR.statusText});
    }));
    resourceXHR.open("GET", options.resourcePath, true);
    resourceXHR.send();
}

答案 1 :(得分:0)

您是否尝试过构建TVML应用的atvjs框架?它可以让您在没有太多噪音的情况下构建和快速构建应用程序原型,从而消除了传统TVML应用程序的潜在麻烦和复杂性。

atvjs中,ajax是作为承诺实现的,您可以执行以下操作:

ATV.Ajax.get('http://your_url')
        .then((response) => /* do something with response */)
        .catch((error) => /* handle errors */ );