2013-07-16 144 views
0

我正在使用以下coffeescript代碼從我的Rails api中檢索json數據,解析json並返回對象數組。JSON解析錯誤:意外的EOF

result = Lungo.Service.get('http://localhost:3000/lists.json') 
lists = JSON.parse(result.response).lists 

我得到這個錯誤:JSON解析錯誤:當我從控制檯執行代碼意外EOF

,一切工作正常。代碼被解析。不過,在我的代碼中,雖然result確實設置爲XMLHttpRequest,但它的響應屬性(包含我的json格式的數據)在訪問時如下所示爲空:result.response

我在Google上搜索,但沒有解決方案解決了我的問題。的result = Lungo.Service.get(url)響應的

實施例:

result = XMLHttpRequest 
| 
___> 
    constructor: XMLHttpRequestConstructor 
    onabort: null 
    onerror: null 
    onload: null 
    onloadend: null 
    onloadstart: null 
    onprogress: null 
    onreadystatechange: function() {if(h.readyState===4){clearTimeout(r);return c(h,f)}} 
    readyState: 4 
    response: "{"lists":[ *data removed for brevity*]}" 
    responseText: "{"lists":[ *data removed for brevity*]}" 
    responseType: "" 
    responseXML: null 
    status: 200 
    statusText: "OK" 
    upload: XMLHttpRequestUpload 
    withCredentials: false 
    __proto__: XMLHttpRequestPrototype 

回答

1

Lungo.Service methods在默認情況下異步的,所以.get()將返回resultresult.response之前已被接收。

它仍然可以出現在日誌中,因爲某些日誌也是異步的,所以它們可能不會嘗試讀取值,直到它變爲可用。

您可以使用「回撥函數」參數指定在response可用時如何做。您還可以指定'json'作爲「Mime類型」。

Lungo.Service.get('http://localhost:3000/lists.json', function (response) { 
    var lists = response.lists; 
    // use `lists` here 
}, 'json'); 
+0

謝謝你的回答。這說得通。但是,我無法獲得該功能的工作。 API是否需要發送特殊狀態(200以外)才能執行回調函數? –