JavaScript and jQuery parse JSON in a loop

Sorry to ask for this, I can't get it to work even when considering other issues ...

I have JSON output in "json.php", for example:

[ {"serverid":"1","servername":"Server One"}, {"serverid":"2","servername":"Server Two"} ] 

I have a script to capture data and parse it in a variable

 var servers; jQuery.get('json.php', function(data) { servers = JSON.parse(data); jQuery('#servers').servers.servername }); 

I have a div to output the results:

 <div id="servers"></div> 

No matter what I try, I always get some kind of

"Uncaught TypeError: Unable to read the error" server server name "undefined".

I would also like to see the results, however I cannot even print it.

Sorry again for another question like this

+4
source share
2 answers

Don't you mean something like that? The jQuery object (which is a reference to your div) knows nothing about servername . In addition, you will need to iterate through an array of elements to get them all:

 servers = $.parseJSON(data); $.each(servers, function(index, value) { $("#servers").text($("#servers").text() + " " + value.servername); }); 

Fiddle: http://jsfiddle.net/H2RC2/1/

+12
source

The error message is all you need. jQuery('#servers') terminates the #servers div in the jQuery object. And this object does not have the property of servers .

Rather, you can use:

  var servers = JSON.parse(data); var res = ''; for(var i = 0; i<servers.length; i++){ res = res + '<p>' + servers[i].servername +'</p>'; } $('#servers').append(res); 
+5
source

Source: https://habr.com/ru/post/1468989/


All Articles