我正在使用 JavaScript
、JQuery
和 Bootstrap
为我的第一个响应式网站构建概念验证。目前我仅对前端进行原型(prototype)设计。
我需要将包含 JSON
内容(在最终应用程序中它将来自服务器端数据库)的文本文件中的内容动态插入到我的 HTML 中。
我的index.html结构如下:
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
...
<ul class="list-unstyled" id="itemList">
<!-- JQuery function will be called when DOM is ready -->
</ul>
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js">/script>
<script src="my.js"></script>
<script>
$( document ).ready("fillInData('text.json')");
</script>
</body>
</html>
在 my.js 中,我有以下代码:
function fillInData (dataFile) {
// remove any existing content
var ft = $('#itemList');
ft.empty();
// populate new stuff from a co-located JSON file
var htmlString = "";
$.getJSON(dataFile, function(data) {
$.each(data.items, function(i, item) {
htmlString += '<li>' + item.name + ...;
...
htmlString += '</li>'
});
});
ft.innerHTML = htmlString;
}
我的问题是,似乎根本没有调用 fillInData
函数。
由于在解析整个 body
之前不应触发 ready
事件,因此我不认为我将钩子(Hook)放置得太低了。
我使用 Chrome 开发工具
进行调试。我在 JS 函数中放置了一个断点,希望从那里逐步执行,但从未到达断点。
我在这里遗漏了一些明显的东西吗?难道这只是一个 RTFM 案例吗?
最佳答案
这是
$(document).ready(function() {
fillInData('text.json');
});
将字符串传递给 $.ready()
并没有真正起作用
编辑:
并修复你的ajax
$.getJSON(dataFile, function(data) {
var htmlString = "";
$.each(data.items, function(i, item) {
htmlString += '<li>' + item.name + ...;
...
htmlString += '</li>'
});
ft.html(htmlString); // it's a jQuery object, and it's async
});
关于javascript - 使用什么事件来触发将 JSON 内容插入到现有 HTML 标记中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22518661/