gpt4 book ai didi

jquery - 解析此 JSON 并为每个对象创建一个新的 div

转载 作者:行者123 更新时间:2023-12-01 08:02:00 24 4
gpt4 key购买 nike

我从 PHP 脚本中获取了此 JSON,目前我正在编写代码。我想做的是,对于每个对象,将响应插入到 div 中。

例如,我想将“句子”插入 div id="sentences",将标题插入 div id="title",并且我想在前面添加或为每个新响应创建一个新响应。

有关如何进行的任何提示?

<script type="text/javascript">
$(document).ready(function() {
console.log("warming up...");
$.getJSON("response.php", function( data ) {
console.log("got JSON");
for (var i = 0; i < data.length; i++) {
var obj = data[i];
console.log(obj.title);
}
});
});
</script>

这是 JSON 响应:

{ "sentences" : [ "The big irony behind the scorched-earth Republican offensive against President Obama’s health-care law is that its expansion of coverage to the uninsured would benefit House districts represented by Republicans nearly as much as those represented by Democrats.",
"Regardless of what other provisions they consider harmful, that posture unavoidably means House Republicans are seeking to “protect” a surprisingly large number of their constituents from the right to obtain health insurance with federal assistance.",
"Recently released census data show that, on average, the share of residents without insurance is almost as high in districts represented by House Republicans as in those represented by Democrats.",
"Slightly more Republicans (107) than Democrats (99) represent districts where the uninsured percentage is above the national average.",
"Massachusetts has the lowest percentage of uninsured due to its state-run health insurance, which has been in place since 2006."
],
"summaryId" : "W76Z7a",
"title" : "Where Are the Uninsured Americans Who Will Benefit From Obamacare?"
}

最佳答案

尝试$.each()因为 data 不是一个数组,它是一个对象。

$(document).ready(function () {
console.log("warming up...");
$.getJSON("response.php", function (data) {
console.log("got JSON");

$.each(data, function (key, obj) {
console.log(key, obj)
$('<div />', {
id: key,
text: obj
}).appendTo('body')
});
});
});

关于jquery - 解析此 JSON 并为每个对象创建一个新的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19209471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com