2014-11-17 47 views
1

在學習Chrome擴展開發時,我嘗試從本地主機服務器加載一些JSON,以便在彈出窗口中顯示它。在Chrome擴展中讀取遠程JSON對象

JSON似乎正在通過,因爲我可以在控制檯中顯示它,但隨後它會'消失'。我無法真正理解發生了什麼,任何幫助將不勝感激。

這裏是我的腳本popup.js

function getLatestContents() { 

    var URL = "http://localhost:8000/api/search/" 
    var items = []; 

    $.getJSON(URL, function(data) { 

     $.each(data, function(idx, val) { 
      var link = "<a href='" + val.url + "'>" + val.name + "</a>"; 
      var element = "<li id='" + val.id + "'>" + link + "</li>" 
      items.push(element); 
     }); 

    }); 

    console.log(items); // prints an array of strings 
    console.log(items.length); // returns 0 (weird) 
    return items; 
} 



$(function(){ 
    var contents = getLatestContents(); 
    console.log(contents); // prints an array of strings 
    console.log(contents.length); // returns 0 (??) 

    if (contents instanceof Array) { 
     console.log("YES"); // returns YES 
     console.log(contents.length); // returns 0 (??) 

     for (var i = 0; i < contents.length; i++) { 
      console.log(i); // nothing happens 
     } 

    } 

}); 

正如你可以看到我試着打印的東西從控制檯推測這是怎麼回事 - 然而數據似乎是互相矛盾。則數組被印刷的,但它的長度看起來是 '0' ...

的manifest.json

{ 
    "manifest_version": 2, 

    "name": "Testing app", 
    "description": "This extension is just a test.", 
    "version": "1.0", 
    "browser_action": { 
    "default_icon": "19x19.png", 
    "default_popup": "popup.html" 
    }, 
    "permissions": [ 
     "http://localhost/*" 
    ] 
} 

popup.html

<!doctype html> 
<html> 
    <head> 
    <title>This is a test</title> 
    <script src="libs/jquery-1.8.3.min.js"></script> 
    <script src="popup.js"></script> 
</head> 
    <body> 
     <h2>Hello</h2> 
     <div id="content"></div> 
    </body> 
</html> 
+1

你的代碼來處理陣列需要是的getJSON處理器裏面的物品。函數getLatestContents可能會返回一個空數組,取決於您的服務器響應的速度。 –

+0

非常感謝這是問題所在! – magicrebirth

回答

0

阿指出由史蒂夫上面的o'Connor:問題在於JSON處理代碼位於AJAX請求代碼之外 - 因此前者在後者之前被錯誤地執行。

這工作:

$(function(){ 
    var contents = getLatestContents(); 
});  


function getLatestContents() { 

    var URL = "http://localhost:8000/api/search/" 


    $.getJSON(URL, function(data) { 
     var items = []; 
     $.each(data, function(idx, val) { 
      var link = "<a href='" + val.url + "'>" + val.name + "</a>"; 
      var element = "<li id='" + val.id + "'>" + link + "</li>" 
      items.push(element); 
     }); 

     $.each(items, function(idx, obj) { 
      $("#content").append(obj); 
     }); 

    }); 

}