
异步问题
ajax异步请求数据完数据后给$scope赋值的时候需要检查$scope的数据更新没有。要不然无法绑定数据。
<!DOCTYPE html>
<html ng-app="test_ajax">
<head>
<meta charset="utf-8">
<title></title>
<script src="angular.js" charset="utf-8"></script>
<script src="jquery.js"></script>
<script>
let mod=angular.module('test_ajax', []);
mod.controller('main', function ($scope){
$.ajax({
url: 'arr.txt',
dataType: 'json',
success(res){
$scope.arr=res;
$scope.$apply(); //检查
},
error(){
alert('错了');
}
});
});
</script>
</head>
<body ng-controller="main">
<ul>
<li ng-repeat="a in arr">{{a}}</li>
</ul>
</body>
</html>
$scope.$apply(); //检查
angularjs方法Post方法请求数据
<!DOCTYPE html>
<html ng-app="test">
<head>
<meta charset="utf-8">
<title></title>
<script src="angular.js" charset="utf-8"></script>
<script>
let mod=angular.module('test', []); mod.config(function ($httpProvider){
$httpProvider.defaults.transformRequest=function (obj){
let arr=[];
for(let name in obj){
arr.push(`${name}=${obj[name]}`);
}
return arr.join('&');
}; $httpProvider.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';
}); mod.controller('main', function ($scope, $http){
$scope.calc=function (){
$http({
method: 'POST',
url: '1.php',
data: {
a: $scope.a,
b: $scope.b
}
}).then(res=>{
alert(res.data);
}, ()=>{
alert('错了');
});
};
});
</script>
</head>
<body ng-controller="main">
<input type="text" ng-model="a">
<input type="text" ng-model="b">
<input type="button" value="计算" ng-click="calc()">
</body>
</html>
为啥POST出问题
AngularJS用的是 application/json 的编码格式大多浏览器不认, 编码格式改成application/x-www-form-urlencoded的编码格式。
angularjs方法get方法请求数据
<!DOCTYPE html>
<html ng-app="test_ajax">
<head>
<meta charset="utf-8">
<title></title>
<script src="angular.js" charset="utf-8"></script>
<script>
let mod=angular.module('test_ajax', []);
mod.controller('main', function ($scope, $http){
$http.get('arr.txt').then((res)=>{
$scope.arr=res.data;
}, (err)=>{
alert('错了');
});
});
</script>
</head>
<body ng-controller="main">
<ul>
<li ng-repeat="a in arr">{{a}}</li>
</ul>
</body>
</html>