所以我从Web服务(用spring创建)中检索JSON结果,如下所示:
const url = "https://www.example.com?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=1";
//divide the url into domain and query
const [domain,query] = url.split("?");
//build a Map out of the query string
const params = new Map(
query.split("&").map(el=>el.split("="))
);
//modification goes here, e.g:
["year","so","sc","pm"].forEach(q => params.delete(q));
/* or to replace a value
params.set("whatever","value")
*/
//build up again:
const result = domain+"?"+[...params].map(el=>el.join("=")).join("&");
我有一个带有以下HTML标记的jsp文件:
[
{"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"}
]
我想将JSON对象中的“nachname”和“id”添加到具有类的div:komponist-id和komponist-name
我尝试了以下来自springIo指南https://spring.io/guides/gs/consuming-rest-jquery/
<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>
不幸的是它不起作用。当我使用$(document).ready(function() {
$.ajax({
url: "myurl"
}).then(function(data) {
$('.komponist-id').append(data.id);
$('.komponist-name').append(data.nachname);
});
});
时,它表明它未定义我做错了什么?
答案 0 :(得分:3)
问题是你的JSON是一个数组。所以你只需要得到它的第一个对象:data[0]
然后获取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>