在chrome扩展中读取远程JSON对象

时间:2014-11-17 15:22:14

标签: javascript json google-chrome

在学习Chrome扩展程序开发时,我尝试从localhost服务器加载一些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
        }

    }

});

正如您所看到的,我尝试在控制台中打印出来以确定正在发生的事情 - 但数据似乎彼此不一致。数组被打印,但其长度似乎是&#39; 0&#39; ...

的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 个答案:

答案 0 :(得分:0)

上面的Steve 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);
        });

    });

}