【发布时间】:2019-09-27 14:57:24
【问题描述】:
我正在使用 AngularJS 和 Django REST API 构建一个 CRUD 应用程序。
我已经成功创建了 get 和 post 方法,但没有得到如何提出请求。我尝试了 stackoverflow 的很多问题和 youtube,但我无法解决。
我当前的控制器是:
app.controller('crudCtrl', function($scope, $http) {
$http.get("http://127.0.0.1:8000/api/v1/contact/?format=json")
.then(function(response) {
$scope.contacts = response.data; //this is get method that displayed all the list of contact
});
$scope.formModel = {}; // this is same input.js, it is POST method to to send data to database
$scope.onSubmit = function () {
console.log("hey, i am submitting");
console.log($scope.formModel);
$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel).
success(function (data) {
console.log(":)");
}).error(function (data) {
console.log(":(");
});
};
$scope.selectUser = function (contact) {
console.log(contact); // it will select the data exactly where you click
$scope.clickedUser = contact;
};
$scope.updateUser = function (argument) { // it will get the form editable exactly which contact you clicked
};
});
我的编辑视图是,当我点击编辑按钮时,表单将出现:
<form>
<input type="text" ng-model="clickedUser.userid">
<input type="text" ng-model="clickedUser.name">
<input type="text" ng-model="clickedUser.email">
<input type="text" ng-model="clickedUser.phone">
<button type="submit" ng-click="updateUser()" data-dismiss="modal">Submit</button>
</form>
需要注意的是,编辑表单在客户端运行良好,但它不会将数据发送到后端/API/数据库。
谁能告诉我我该怎么做$http.put 请求?我尝试了 w3school、youtube 和 stackoverflow 问题。
我得到了巨大的解决方案,但我无法解决它。
这是我的 api 端点:http://127.0.0.1:8000/api/v1/contact/ 所以如果我想更新特定字段,我必须通过这个 url:http://127.0.0.1:8000/api/v1/contact/1 在 url 的末尾是 id
希望你明白
【问题讨论】:
-
就像
$http.post方法一样,$http.put方法也可用。请尝试。
标签: angularjs django-rest-framework