遇到的问题是这样的:
前端页面demo2.xml
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<meta charset="UTF-8">
<title>demo2</title>
<script src="angular.min.js"></script>
<script>
var brandapp = angular.module("youlexuan", []);
brandapp.controller("brandController", function ($scope, $http) {
$scope.brandlist = [{name:"测试",id:0,firstChar:"C"}];
$scope.getBrandList = function () {
$http.post("http://127.0.0.1:9101/brand/all.do").success(function (aaa) {
$scope.brandlist = aaa;
})
}
})
</script>
</head>
<body ng-app="youlexuan" ng-controller="brandController">
<button ng-click="getBrandList()">获取品牌集合</button>
{{brandlist}}
<table border="1" width="50%">
<tr ng-repeat="brand in brandlist">
<td>{{brand.id}}</td>
<td>{{brand.name}}</td>
<td>{{brand.firstChar}}</td>
</tr>
</table>
</body>
</html>
本段代码没有错误。
直接访问http://127.0.0.1:9101/brand/all.do路径是没有问题的,可以看到获取的数据。但是通过angular中的$http请求
$http.post("http://127.0.0.1:9101/brand/all.do").success(function (aaa) {
$scope.brandlist = aaa;
})
,获取不到后台数据。
后来转到火狐浏览器调试,发现
接着对此问题进行了学习。
解决方法
进入controller层,修改调用的方法
原图:
对原图中代码进行修改,修改后:
即:在请求响应后,返回数据前,添加响应头 Access-Control-Allow-Origin,值为*,就是匹配任意请求地址