【发布时间】:2010-07-22 03:04:03
【问题描述】:
我正在尝试使用 JQuery 的 ajax 方法从 JSON 文件中获取数组。具体来说,我想在文档加载时发出 ajax 请求,并在其他功能中使用获取的数据。 这是我的代码:
$(document).ready(function() {
getJSON();
clickEvents();
});
function getJSON() {
$.getJSON('goods.js', function(data) {
crazyFun(data.Goods);
addScores(data.karma);
});
}
}
function addScores(karma) {
$('#karmaYinYangScore').append(karma[0].karmaYinYangScore);
$('#KarmaGiveScore').append(karma[0].KarmaGiveScore);
$('#KarmaTakeScore').append(karma[0].KarmaTakeScore);
$('#ItemsGiveScore').append(karma[0].ItemsGiveScore);
$('#ItemsTakeScore').append(karma[0].ItemsTakeScore);
}
function crazyFun(Goods) {
for (var i = 0; i < Goods.length; i++) {
var alpha= $('#template').clone();
alpha.removeAttr('id');
alpha.find('div.picture').attr('id', Goods[i].picture);
alpha.find('h2').html(Goods[i].header);
alpha.find('p').html(Goods[i].text);
alpha.find('div.notification').attr('id', Goods[i].notification);
$('#repeater').append(alpha);
}
}
karma 和 Goods 是 JSON 文件中数组的名称。
我做错了什么?
这是我的因果关系 JSON 数组:
{
Goods : [{
"header": "Apple",
"text": "hi"
"picture": "appleImage",
"notification": "appleNote"
}, {
"header": "Pear",
"text": "hi",
"picture": "pearImage",
"notification": "pearNote"
}, {
"header":hi",
"picture": "bananaImage",
"notification": "bananaNote"
}, {
"header": "Dog",
"text": "hi",
"picture": "dogImage",
"notification": "dogNote"
}, {
"header": "Cat",
"text": "hi",
"picture": "catImage",
"notification": "catNote"
}, {
"header": "Snake",
"text": "hi",
"picture": "snakeImage",
"notification": "snakeNote"
}],
karma : [{
"karmaYinYangScore": "200",
"KarmaGiveScore": "40",
"KarmaTakeScore": "99",
"ItemsGiveScore": "20",
"ItemsTakeScore": "77"
}];
}
【问题讨论】:
-
您的 JSON 文件是什么样的?你有什么问题?你的回调函数的定义是错误的,但是没有看到JSON就没什么好说的了。
-
JSON 结构良好。当我在 html 文件中调用 JSON 时,一切正常。
-
没关系。为了帮助您,我们需要知道它的外观。
-
好的,谢谢。如果这是
goods.js,则此文件不是 JSON 文件。它是 JavaScript。如果你想使用getJSON,这个文件需要包含一个像{"karma": [...], "goods": [...]}这样的JSON字符串
标签: javascript jquery json