AngularJS XMLHttpRequest

$http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。

$http.get('someUrl',config).then(successCallback,errorCallback);
$http.post('someUrl',data,config).then(successCallback,errorCallback);

废弃声明 (v1.5)

v1.5 中$http 的 success 和 error 方法已废弃。使用 then 方法替代。

客户端代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="angular-1.6.3/angular.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li>{{names.name+' '+ names.gender}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', [])
.config(['$sceDelegateProvider', function($sceDelegateProvider) {
// We must whitelist the JSONP endpoint that we are using to show that we trust it
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'http://localhost:58993/**' //服务器端运行的URL
]);
}]);//很重要,要先设置为信任的url
app.controller('myCtrl', ['$scope', '$http', '$templateCache',
function($scope, $http) {
$http.jsonp('http://localhost:58993/home/TestJSONP?name=2').
then(function(response) {
$scope.names = response.data;
}, function(response) {
alert(response.data)
});
}]);
</script>
</body>
</html>

注意:以上代码的 JSONP 跨域请求。

C#服务端代码

public void TestJSONP()
{
string callback = Request.QueryString["callback"];
var name = Request.QueryString["name"];
var json = "{'name':2,'gender':'男'}";
//JSONP格式:回调函数名(json格式参数)
string result = string.Format("{0}({1})", callback, json);
Response.ContentType = "application/json";
Response.Write(result);
}

最新文章

  1. 非对称技术栈实现AES加密解密
  2. C#-ASP.NET MVC-架构【1】-自定义错误页
  3. sql高级语句大全
  4. 在一台机器上模拟mongodb分片
  5. jquery获取所有被选中checkbox
  6. Android中Adapter之BaseAdapter使用
  7. RPC、SQL、NFS属于OSI的哪一层
  8. ubuntu16.04 搭建 Mysql服务器
  9. JAVA 异常对于性能的影响
  10. [CSS]学习总结
  11. Flasback数据库(闪回数据库)
  12. (三)跟我一起玩Linux网络服务:DHCP服务配置之主服务器配置
  13. JDBC基本知识
  14. SEOer怎样安排一天的工作
  15. Light OJ 1095 Arrange the Numbers(容斥)
  16. Advanced Sort Algorithms
  17. IIS异常:CS0016: 未能写入输出文件“c:\WINDOWS\Microsoft.NET\Framework\.。。”--“拒绝访问
  18. docker save提示no space left on device错误
  19. NodeJS笔记(三)-创建第一个NodeJS web项目 Express
  20. 负载均衡----实现配置篇(Nginx)

热门文章

  1. 第5章 不要让线程成为脱缰的野马(Keeping your Threads on Leash) ---线程优先权(Thread priority)
  2. 第4章 同步控制 Synchronization ----死锁(DeadLock)
  3. JSON依赖的选择
  4. Windows下 如何添加开机启动项
  5. Coin Change (IV) (dfs)
  6. 如何创建一个Django项目
  7. ZOJ-2091-Mean of Subsequence (反证法的运用!!)
  8. Mybatis了解(配置)
  9. 深入浅出 SpringMVC - 1
  10. vim搭建笔记