【问题标题】:AngularJS $http PUT requestAngularJS $http PUT 请求
【发布时间】: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


【解决方案1】:

你也可以试试

$http({method: "PUT", url: URL}).
        then(
           function(response) {
        }, function(response) {
      });

【讨论】:

    【解决方案2】:

    你可以只使用角度放置吗?

    见:https://docs.angularjs.org/api/ng/service/$http#put

    var clientData = {
       text: "Put this somewhere"
    };
    $http.put( url, clientData ).then( function( serverResponse ) {
        console.log(serverResponse);
    },( error )=>{
        console.log(serverError);
    });
    

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      相关资源
      最近更新 更多