AngularJS实现ajax请求的方法
本文实例讲述了AngularJS实现ajax请求的方法。分享给大家供大家参考,具体如下:
【HTML代码】
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<metaname="viewport"content="width=device-width,user-scalable=no,initial-scale=1">
<linkrel="stylesheet"type="text/css"href=""/>
<title>angularjs实现ajax</title>
</head>
<bodyng-app="HelloAjax">
<divng-controller="HelloAjax">
<form>
<inputtype="text"ng-model="username"/>
<inputtype="text"ng-model="email"/>
</form>
<table>
<trng-repeat="userinusers">
<td>{{user.username}}</td>
<td>{{user.email}}</td>
</tr>
</table>
<buttonng-click="get_more();">getmore</button>
</div>
</body>
<scripttype="text/javascript"src="./js/angular.min.js"charset="utf-8"></script>
<scripttype="text/javascript"src="ajax.js"charset="utf-8"></script>
</html>
【js代码ajax.js】
varmyModule=angular.module("HelloAjax",[]);
myModule.controller("HelloAjax",["$scope","$http",functionHelloAjax($scope,$http){
/*
$scope.users=[{'username':"zhangsan","email":"zs@11.com"},
{'username':"zhangsan2","email":"zs@22.com"},
{'username':"zhangsan3","email":"zs@33.com"}];
*/
$scope.get_more=function(){
$http({
method:"POST",
url:"./ajax.php",
data:{'username':$scope.username,
'email':$scope.email
}
}).
success(function(data,status){
//$scope.status=status;
$scope.users=data;
}).
error(function(data,status){
//$scope.data=data||"Requestfailed";
//$scope.status=status;
});
}
}]);
【PHP代码ajax.php】
<?php
//获取参数
$data=file_get_contents("php://input");
$user=json_decode($data);
//查询数据库
$conn=mysql_connect("localhost","root","");
mysql_select_db("test");
$sql="selectusername,emailfromusers";
$res=mysql_query($sql,$conn);
$users=array();
while($row=mysql_fetch_assoc($res)){
$users[]=$row;
}
//当然这里简化了插入数据库
$users[]=array('username'=>$user->username,
'email'=>$user->email);
//返回数据库
echojson_encode($users);
更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《AngularJS入门与进阶教程》、《jQuery常用插件及用法总结》、《jquery中Ajax用法总结》、《JavaScript中ajax操作技巧总结》及《PHP+ajax技巧与应用小结》
希望本文所述对大家AngularJS程序设计有所帮助。