我正在尝试附加以下 JSON 数据:
[
{
"idfruits": "1",
"fruit": "Apple"
},
{
"idfruits": "2",
"fruit": "Orange"
},
{
"idfruits": "3",
"fruit": "Banana"
},
{
"idfruits": "4",
"fruit": "Raspberry"
},
{
"idfruits": "5",
"fruit": "Coconut"
}
]
使用以下代码:
<script type="text/javascript">
$(function () {
jQuery.ajax({
url: "index.php",
type: "POST",
dataype: "json",
async: false,
success: function (data) {
console.log(data);
var items = [];
$.each(data, function (key, fruit_info) {
items.push('<li id="fruit_' + fruit_info.idfruits + '">' + fruit_info.fruit + '</li>');
});
$(items.join('')).appendTo('#listy');
}
});
});
</script>
不幸的是,代码给出了以下错误:
TypeError: invalid 'in' operand obj
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
我的目标是创建一个通用方法,它总是将第一个 JSON 值解析key
为val
.
这可能吗?