时间:2021-05-01 09:31:48 | 栏目:AngularJS | 点击:次
本文主要介绍的是Angular.JS内置服务$http对数据库的增删改操作的相关内容,分享出来供大家参考学习,下面来看看详细的介绍:
一、使用$http查询MySQL数据
angular.module('app',[]) .controller('MyCtrl',function ($scope,$http) { $http.get('http://127.0.0.1:80/user/getUsers') .success(function (resp) { console.log(resp); }) .error() //jQuery /*$.get('url',function (data) { });*/ })
对应的后台Java代码:
public void getUsers(){ List<User> users = User.dao.find("select * from t_user"); renderJson(Users); }
二、$http实现对数据的增删改
(1)$http带参数发送请求
(2)对MySQL数据增删改
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>AngularJS $http</title> <link rel="stylesheet" href="css/foundation.min.css" rel="external nofollow" > <style type="text/css"> html,body{font-size:14px;} </style> </head> <body style="padding:10px;" ng-app="app"> <div ng-controller="MyCtrl"> <input type="text" ng-model="id"> <input type="text" ng-model="name"> <button class="button" onclick="addUser()">添加</button> <button class="button" onclick="delUser()">删除</button> </div> </body> <script src="js/angular.min.js"></script> <script src="app.js"></script> </html>
angular.module('app', []) .controller('MyCtrl', function ($scope, $http) { $scope.id=" "; $scope.name=" "; $scope.addUser = function () { $http.post('http://127.0.0.1:80/user/addUser',{id:$scope.id, name:$scope.name}) .success(function (resp) { if(resp.success){ alert("添加成功"); } }) } $scope.delUser = function () { $htp.post('http://127.0.0.1:80/user/delUser',{id:$scope.id}) .success(function () { if(resp.success){ alert('删除成功'); } }) } })
后台Java代码:
public void addUser(){ String id = getPara("id"); String name = getPara("name"); User user = new User(); boolean isok = false; if(id != null && id.equals("")){ isok = user.set("id",id).set("name",name).update(); }else{ isok = user.set("name",name).save(); } renderJson("seccess",isok); } public void delUser(){ String id = getPara("id"); boolean isok = User.dao.deleById(id); renderJson("seccess",isok); }
总结