每 2 秒,我发送一个返回的 POST:
[{"a":false,"i":"58","b":"sergio","p":"0,22","t":15},
{"a":false,"i":"59","b":"sergio","p":"0,23","t":15},
{"a":false,"i":"60","b":"sergio","p":"0,14","t":15},
{"a":false,"i":"61","b":"sergio","p":"0,07","t":15}]
我有一个捕获此信息的 Javascript 函数,我希望它也能解析 JSON 并将值放入相应的元素中。
function updateauctions(response) {
//Parse JSON and place into HTML elements.
//For debug purposes.
alert(response);
}
我正在使用 jQuery,我想知道如何获取 JSON 值,并将它们放入 HTML 元素中。
div .auctionbox
的示例:
<div id="60" class="auctionbox gold">
//Other things here.
</div>
例如,我有 n
个类为 .auctionbox
的 div,每个 div 的 ID 也都是 #i
.所以每个 JSON 对象都对应一个 .auctionbox
。我如何将 JSON 的 p
值放入适当的 #i
、.auctionbox
?
通过这个简单的示例,我可以开始处理其他需求,我只需要一点点插入。 :)
谢谢。
最佳答案
如果您需要执行一些特定的 html + css,则使用模板的解决方案
html
<div id="data">
<div class="template auctionbox"></div>
</div>
js
var json = '[{"a":false,"i":"58","b":"sergio","p":"0,22","t":15},' +
'{"a":false,"i":"59","b":"sergio","p":"0,23","t":15},' +
'{"a":false,"i":"60","b":"sergio","p":"0,14","t":15},' +
'{"a":false,"i":"61","b":"sergio","p":"0,07","t":15}]';
var data = $.parseJSON(json);
var $template = $('.template');
$(data).each(function() {
var $element = $template.clone().removeClass('template').appendTo('#data');
$element.attr('id', this.i);
$element.html(this.p);
});
关于jquery - 将来自 json 响应的 JSON 值放入 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7504163/