Adding JSON Data to ListView

I am trying to add the following JSON data:

[ { "idfruits": "1", "fruit": "Apple" }, { "idfruits": "2", "fruit": "Orange" }, { "idfruits": "3", "fruit": "Banana" }, { "idfruits": "4", "fruit": "Raspberry" }, { "idfruits": "5", "fruit": "Coconut" } ] 

With the 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 the following error:

 TypeError: invalid 'in' operand obj typeof length === "number" && length > 0 && ( length - 1 ) in obj ); 

My goal was to create a generic method that always parses the first JSON value as key and the second as val .
Is it possible?

+4
source share
2 answers

No. ECMAScript defines the behavior of the hash 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, value, and set of attributes.

You cannot assume that given a hash such as {"idfruits":"1","fruit":"Apple"} , the identifier will be first and the fruits will be second. You will need to name 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> 
+1
source

I believe you want to use fruit instead of value

try it

  $.each(data, function(key, val) { items.push('<li id="' + this.fruit+ '">' + this.fruit + '</li>'); }); 
0
source

All Articles