将JSON数据追加到ListView [英] Appending JSON data to ListView
问题描述
我正在尝试附加以下JSON数据:
I am trying to append following JSON data:
[
{
"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>
不幸的是,代码给出了以下错误:
Unfortunately the code gives following error:
TypeError: invalid 'in' operand obj
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
我的目标是创建一个 generic 方法,该方法始终将第一个JSON值解析为key
,将第二个JSON值解析为val
.
这可能吗?
My goal was to make a generic method that always parses first JSON value as key
and second as val
.
Is this possible?
推荐答案
否. ECMAScript指定这样的哈希行为: http://bclary.com/2004/11/07 /#a-8.6
No. ECMAScript specifies hash behavior as such: http://bclary.com/2004/11/07/#a-8.6
对象是属性的无序集合.每个属性都包含一个名称,一个值和一组属性.
An Object is an unordered collection of properties. Each property consists of a name, a value and a set of attributes.
您不能假设给定像{"idfruits":"1","fruit":"Apple"}
这样的哈希,id将是第一个,水果将是第二个.您需要按名称称呼他们.
You cannot assume that given a hash like {"idfruits":"1","fruit":"Apple"}
, the id will be first and the fruit will be second. You will need to call them by name.
顺便问一下,很好的问题.
Very good question, by the way.
要做你想做的事:
<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>
这篇关于将JSON数据追加到ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!