2015-11-02 66 views
0

我正在爲Apple TV構建TVML應用程序。當我運行此代碼向遠程服務器發出請求時,出現此錯誤:SyntaxError:JSON解析錯誤:意外的EOF。我試圖從application.js文件運行代碼並填充應用程序的視圖。任何幫助表示讚賞。SyntaxError:JSON解析錯誤:使用TVJS框架的意外EOF

loadData("https:/xxx.xxx.net") 

    function loadData(url) { 
     var xhr; 
     var jsonData; 
     xhr = new XMLHttpRequest(); 
     xhr.responseType = "json"; 
     xhr.onreadystatechange = function() { 
     if (xhr.status == 200) { 
     jsonData = JSON.parse(xhr.responseText); 
     console.log(jsonData); 
     }; 
     }; 

     xhr.open("GET", url, true); 
     xhr.send(); 
     if (jsonData != undefined) { return jsonData } 
    }; 

其他設備,如Roku使用相同的API和功能正確。

{ 
    "playlists": [ 
     { 
      "id": 8, 
      "title": "test", 
      "description": "new playlist test", 
      "cover_url": "http://598-1446309178.png" 
     }, 
     { 
      "id": 9, 
      "title": "test1", 
      "description": "lives", 
      "cover_url": "http://754-1446309324.jpg" 
     }, 
     { 
      "id": 10, 
      "title": "test2", 
      "description": "video games", 
      "cover_url": "http://6173-1446310649.jpg" 
     }, 
     { 
      "id": 11, 
      "title": "test4", 
      "description": "little", 
      "cover_url": "http://dd6-1446312075.jpg" 
     } 
    ] 
} 
+1

你可以發佈JSON輸出或它的一個樣本嗎? – Griffith

+2

一旦你解決了無效的JSON,你將會遇到的下一個問題是你的'loadData'將會返回非undefined –

回答

0

您可以使用Safari調試您的應用程序。 一旦你的應用程序運行,選擇「開發/模擬器/ {你的應用程序}」。 你的代碼部分看起來不錯,但檢查xhr.responseText是什麼,它可能會返回空。 你其他錯誤是,當你使用下面的「真」,你正在一個異步請求:

xhr.open("GET", url, true); 

你需要一個回調提供給您的功能和使用該回調。 我使用錯誤的第一個回調風格。

function loadData(url, callback) { 
     var xhr; 
     var jsonData; 
     xhr = new XMLHttpRequest(); 
     xhr.responseType = "json"; 
     xhr.onreadystatechange = function() { 
     if (xhr.status == 200) { 
     try{ 
      jsonData = JSON.parse(xhr.responseText); 
     } catch(e) { 
      return callback('json parsing error'); 
     } 
     callback(null, jsonData); 
     console.log(jsonData); 
     }; 
     }; 

     xhr.open("GET", url, true); 
     xhr.send(); 
    };