AngularJS – 与服务器通讯

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

运行效果图:

image001

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值