$http service и взаимодействие с БД
Вложений: 2
У меня есть сервис в котором описаны функции вывода данных, добавления данных и удаления данных
app.service("friendService", function( $http, $q ) { // Return public API. return({ addFriend: addFriend, getFriends: getFriends, removeFriend: removeFriend }); // --- // PUBLIC METHODS. // --- // I add a friend with the given name to the remote collection. function addFriend( name ) { var request = $http({ method: "post", url: "server.php", params: { action: "add" }, data: { name: name } }); return( request.then( handleSuccess, handleError ) ); } // I get all of the friends in the remote collection. function getFriends() { var request = $http({ method: "get", url: "server.php", params: { action: "get" } }); return( request.then( handleSuccess, handleError ) ); } // I remove the friend with the given ID from the remote collection. function removeFriend( id ) { var request = $http({ method: "delete", url: "server.php", params: { action: "delete" }, data: { id: id } }); return( request.then( handleSuccess, handleError ) ); } function editFriend( id, name ) { var request = $http({ method: "put", url: "server.php", params: { action: "put" }, data: { id: id, name: name } }); return( request.then( handleSuccess, handleError ) ); } // --- // PRIVATE METHODS. // --- // I transform the error response, unwrapping the application dta from // the API response payload. function handleError( response ) { // The API response from the server should be returned in a // nomralized format. However, if the request was not handled by the // server (or what not handles properly - ex. server error), then we // may have to normalize it on our end, as best we can. if ( ! angular.isObject( response.data ) || ! response.data.message ) { return( $q.reject( "An unknown error occurred." ) ); } // Otherwise, use expected error message. return( $q.reject( response.data.message ) ); } // I transform the successful response, unwrapping the application data // from the API response payload. function handleSuccess( response ) { return( response.data ); } } ); и есть контроллер где эти функции вызываются app.controller("DemoController", function( $scope, friendService ) { // I contain the list of friends to be rendered. $scope.friends = []; // I contain the ngModel values for form interaction. $scope.form = { name: "" }; loadRemoteData(); // --- // PUBLIC METHODS. // --- // I process the add-friend form. $scope.addFriend = function() { // If the data we provide is invalid, the promise will be rejected, // at which point we can tell the user that something went wrong. In // this case, I'm just logging to the console to keep things very // simple for the demo. friendService.addFriend( $scope.form.name ) .then( loadRemoteData, function( errorMessage ) { console.warn( errorMessage ); } ) ; // Reset the form once values have been consumed. $scope.form.name = ""; }; // I remove the given friend from the current collection. $scope.removeFriend = function( friend ) { console.log(friend.id); // Rather than doing anything clever on the client-side, I'm just // going to reload the remote data. friendService.removeFriend( friend.id ) .then( loadRemoteData ) ; }; $scope.editFriend = function( friend ) { // Rather than doing anything clever on the client-side, I'm just // going to reload the remote data. friendService.editFriend( friend.id ) .then( loadRemoteData ) ; }; // --- // PRIVATE METHODS. // --- // I apply the remote data to the local scope. function applyRemoteData( newFriends ) { $scope.friends = newFriends; } // I load the remote data from the server. function loadRemoteData() { // The friendService returns a promise. friendService.getFriends() .then( function( friends ) { applyRemoteData( friends ); } ) ; } } ); и конечно существует сервер где обрабатываются запросы в БД <?php define("DB_HOST", "localhost"); define("DB_LOGIN", "root"); define("DB_PASSWORD", "000000"); define("DB_NAME", "users"); mysql_connect(DB_HOST, DB_LOGIN, DB_PASSWORD); mysql_select_db(DB_NAME); if ($_SERVER['REQUEST_METHOD'] == 'GET') { $result = mysql_query("select * from `name` "); $data = array(); while ($row = mysql_fetch_array($result)) { $data[] = $row; } print json_encode($data); } if ($_SERVER['REQUEST_METHOD'] == "POST") { $data = json_decode(file_get_contents("php://input")); $name = mysql_real_escape_string($data->name); $email = mysql_real_escape_string($data->email); $telephone = mysql_real_escape_string($data->telephone); $city = mysql_real_escape_string($data->city); $address = mysql_real_escape_string($data->address); $state = mysql_real_escape_string($data->state); $zip = mysql_real_escape_string($data->zip); $sql = "INSERT INTO `name`(`name`)VALUES('".$name."')"; mysql_query($sql) or die(mysql_error()); } if($_SERVER['REQUEST_METHOD'] == 'DELETE') { $params = array(); parse_str(file_get_contents('php://input'), $params); $id = $params['id']; $sql = "DELETE FROM name WHERE id = $id"; mysql_query($sql) or die(mysql_error()); } ?> Вывод и добавление работают правильно, а вот удаление нет, но и ошибок никаких не выдает, если нажать на кнопку удалить, то вроде все правильно работает если посмотреть в консоль, запрос вроде срабатывает, и id нужный тоже получает, пожалуйста кто понимает в чем дело объясните а то надо уже сдавать работу, и все уже готово, только вот тут уперся в тупик...( |
Часовой пояс GMT +3, время: 17:52. |