Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript & jQuery parse JSON in loop

Sorry about asking this, I can't get it to work even with looking at other questions...

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

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

I have a script, to grab the data & parse it into 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 to:

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

Whatever I try, I always get some kind of

"Uncaught TypeError: Cannot read property 'servername' of undefined" error.

I'd also like to look around the results, however I can't even get it to print atm.

Again sorry for another question like this

like image 955
Alias Avatar asked Mar 13 '13 14:03

Alias


People also ask

Whats JavaScript is used for?

JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else.

Which is better HTML or JavaScript?

You can add some static effects to make your website look more appealing with HTML. The content can be manipulated for creating dynamic pages with JavaScript. The page can be dynamic and interactive in real-time. We cannot manipulate the content present on a web page with HTML- it will be static.

Is JavaScript same as Python?

Python's "object-based" subset is roughly equivalent to JavaScript. Like JavaScript (and unlike Java), Python supports a programming style that uses simple functions and variables without engaging in class definitions.

Is JavaScript easy to learn?

Arguably, JavaScript is one of the easiest programming languages to learn, so it serves as a great first language for anyone brand new to coding. Even the most complex lines of JavaScript code can be written one by one, in fragments. It can also be tested in the web browser at the same time.


2 Answers

Don't you mean something like this? the jQuery object (which is a reference to your div) knows nothing about servername. Also, you'll need to iterate through the array of items in order to get them all:

servers = $.parseJSON(data);

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

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

like image 176
mattytommo Avatar answered Oct 07 '22 00:10

mattytommo


The error message is all you need. The jQuery('#servers') wrap the #servers div in the jQuery object. And this object has got no property such as servers.

Rather you could 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);
like image 25
Alberto De Caro Avatar answered Oct 06 '22 23:10

Alberto De Caro