AngularJS学习篇(九)

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);
}    

 

posted on 2017-03-29 23:46  IT-HourseMan  阅读(234)  评论(0编辑  收藏  举报