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
运行效果图:
![](http://www.ioniconline.com/wp-content/uploads/2015/11/image0013.png)
相关文章推荐
- AngularJs $resource 高大上的数据交互
- angularjs中provider、factory和service三者的写法与区别
- AngularJS directive简述
- AngularJS处理ASP.Net MVC Json返回日期
- AngularJS进阶(十六)脏值检查
- AngularJS进阶(十六)脏值检查
- angularjs之ui-bootstrap和ui-router结合使用
- angularjs之ui-bootstrap的使用
- angularjs-ui-router的使用
- angularjs指令的使用
- 我的第一篇博客随笔:关于angularjs API的理解心得。angular.bind() angular.boostrap()
- AngularJS进阶(十五)Cookie 'data' possibly not set or overflowed because it was too large
- AngularJS进阶(十五)Cookie 'data' possibly not set or overflowed because it was too large
- 前端使用AngularJS的$resource,后端ASP.NET Web API,实现增删改查
- AngularJS进阶(十四)AngularJS灵异代码事件
- AngularJS进阶(十四)AngularJS灵异代码事件
- 了解angular2--template(译)
- AngularJS Promise
- AngularJS过滤器
- angular模块控制器分离二