Reputation: 4115
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"
}
]
With following code:
<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 );
My goal was to make a generic method that always parses first JSON value as key
and second as val
.
Is this possible?
Upvotes: 4
Views: 2015
Reputation: 27247
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.
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.
To do what you want:
<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>
Upvotes: 1
Reputation: 23208
I believe you want use fruit
instead of value
Try this
$.each(data, function(key, val) {
items.push('<li id="' + this.fruit+ '">' + this.fruit + '</li>');
});
Upvotes: 0