在学习 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>
最佳答案
上面 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/