您的位置:首页 > Web前端 > AngularJS

AngularJS – 与服务器通讯

2015-12-03 16:31 766 查看


您可自由转发此文, 但请保留出处: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

运行效果图:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: