consuming API JSon calls through TVJS-tvOS

前端 未结 6 821
终归单人心
终归单人心 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条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 10:59

    If you want to call the request on app launch, just add in 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);
    }
    

    }); }

    In presenter.js add a method:

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

提交回复
热议问题