这是嵌入式Jetty中带有Jersey的后端Java Side。
@GET
@Path("/jason")
@Produces({MediaType.APPLICATION_JSON})
public MyJaxBean getMyBean() {
MyJaxBean myJB = new MyJaxBean();
myJB.add("Hello", 1);
myJB.add("World", 2);
return myJB;
}
用curl检查是否带回了这个文本
{ “人”:[{ “名称”: “你好”, “年龄”:1},{ “名称”: “世界”, “年龄”:2}]}
在HTML页面中使用它
<p id="demo"></p>
<button onclick="doRequest()">REQUEST !</button>
<script>
"use strict";
function doRequest(){
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/api/entry-point/jason";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
var myHTML = iterateObject(myArr);
document.getElementById("demo").innerHTML = myHTML
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function iterateObject(myArr) {
var out = '';
myArr.person.forEach(function(p) {
out+= p.name + ',' + p.age + '<br>';
});
return out;
}
</script>
带回来
您好,1 世界,2
然而,使用AngularJS尝试不会显示Jason Call
的声音 <!DOCTYPE html>
<html>
<script src= "http://localhost:8080/ressources/angular.js"></script>
<body>
<h2>AngularJS doing a JSON HTTP Request</h2>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="p in persons">
{{ p.name + ', ' + p.age }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:8080/api/entry-point/jason")
.success(function (response) {$scope.persons = response.records;});
});
</script>
</body>
</html>
用
替换http.get$scope.persons = [{name:"Hello", age:1},{name:"World",age:2}]
确实有效。
任何想法媒体类型或AngularJS示例有什么问题? 感谢您的帮助
答案 0 :(得分:1)
将<li ng-repeat="p in names">
更改为<li ng-repeat="p in persons">
。您要在persons
对象中设置值,但在视图中使用names
。