您可自由转发此文, 但请保留出处:Ionic在线学习网站 http://www.ioniconline.com
$http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。
AngularJS_http.html:
<!DOCTYPE html>
<html>
<script src="http://apps.bdimg.com/libs/angular.js/1.3.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<p> {{res}} </p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.jsonp("http://192.168.4.254:7777/test_ng/")
.success(function(response) {$scope.res=response.url;});
});
</script>
</body>
</html>
注意:以上代码的 get 请求是跨域的服务器,一般跨域服务器默认情况下, 都是不能这样访问的。需要在web服务器端, 设置如下属性:
"Access-Control-Allow-Origin"
"Access-Control-Allow-Methods"
"Access-Control-Max-Age"
"Access-Control-Allow-Headers"
服务器接口代码片段:
def test_ng(request):
url = "http://www.baidu.com"
name="angularjs"
context_dict = {'url': url, 'title': name}
response = HttpResponse(json.dumps(context_dict), content_type="application/json")
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "*"
return response
运行效果图: