javascript - 在 Chrome 扩展中读取远程 JSON 对象

标签 javascript json google-chrome

在学习 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”...

ma​​nifest.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>

最佳答案

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

    });

}

关于javascript - 在 Chrome 扩展中读取远程 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26975929/

相关文章:

google-chrome - Firefox/Chrome 调试器 - 自动打开

javascript - 向禁用按钮添加类或样式

json - 你如何让 Jackson 使用 Kotlin 默认参数作为缺失值?

json - 无法将带有点的键(键路径)添加到类型为 : Schema. Types.Mixed 的 Mongoose 字段

json - Jolt Transformation - 小写所有键?

css - 如何存储从网站加载的 CSS 文件并将它们应用到另一个网站?

html - 表格宽度 100% 偏移一个像素(取决于实际宽度)

javascript - 如何知道电子邮件是否已经在firebase身份验证中注册,javascript?

javascript - 拖动时多次触发谷歌地图事件 bounds_changed

javascript - JSON在动态添加元素后排序