TheWandererr
TheWandererr

Reputation: 514

cannot write JSON result from webserive to html

So I retrieve a JSON result from a webservice(created with spring) which looks like this:

[
{"id":34,"nachname":"Mozart","vorname":"Wolfgang Amadeus","namenspraedikat":"","instrumentId":0,"geburtsdatum":"27.01.1756","herkunftsland":"Salzburg","sterbedatum":"05.12.1791","plz":null,"ort":null,"straße":null,"handy":null,"fax":null,"email":"","discriminator":"Komponist"}
]

I got a jsp file with following HTML markup:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/repertoireController.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Insert title here</title>
</head>
<body>
<div></div>
<div class="komponist-id"></div>
<div class="komponist-name"></div>
</body>
</html>

I want to add the "nachname" and the "id" from the JSON object to the divs with the classes: komponist-id and komponist-name

I tried the following which is from the springIo guides https://spring.io/guides/gs/consuming-rest-jquery/

$(document).ready(function() {
    $.ajax({
        url: "myurl"
    }).then(function(data) {
       $('.komponist-id').append(data.id);
       $('.komponist-name').append(data.nachname);
    });
});

Unfortunately it doesn't work. When i use alert(data.id) it shows that it is undefined what am I doing wrong?

Upvotes: 0

Views: 45

Answers (1)

DenseCrab
DenseCrab

Reputation: 1313

The problem is that your JSON is an array. So you just need to get the first object of it like: data[0] and then get the id/nachname.

var data = [
{"id":34,"nachname":"Mozart","vorname":"Wolfgang Amadeus","namenspraedikat":"","instrumentId":0,"geburtsdatum":"27.01.1756","herkunftsland":"Salzburg","sterbedatum":"05.12.1791","plz":null,"ort":null,"straße":null,"handy":null,"fax":null,"email":"","discriminator":"Komponist"}
];

$(document).ready(function() {
       $('.komponist-id').append(data[0].id);
       $('.komponist-name').append(data[0].nachname);
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/repertoireController.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Insert title here</title>
</head>
<body>
<div></div>
<div class="komponist-id"></div>
<div class="komponist-name"></div>
</body>
</html>

Upvotes: 3

Related Questions