【问题标题】:How Access angular passed parameters in django views如何在 django 视图中访问角度传递参数
【发布时间】:2017-04-18 15:28:24
【问题描述】:

我试图在 django 中使用 angular $http.post 方法发布数据,我想知道如何在我的 django 视图中访问该参数值:-

这是我的 controller.js

    var nameSpace = angular.module("ajax", ['ngCookies']);

nameSpace.controller("MyFormCtrl", ['$scope', '$http', '$cookies',
function ($scope, $http, $cookies) {
    $http.defaults.headers.post['Content-Type'] = 'application/json';
    // To send the csrf code.
    $http.defaults.headers.post['X-CSRFToken'] = $cookies.get('csrftoken');

    // This function is called when the form is submitted.
    $scope.submit = function ($event) {
        // Prevent page reload.
        $event.preventDefault();
        // Send the data.
        var in_data = jQuery.param({'content': $scope.card.content,'csrfmiddlewaretoken': $cookies.csrftoken});
        $http.post('add_card/', in_data)
          .then(function(json) {
            // Reset the form in case of success.
            console.log(json.data);
            $scope.card = angular.copy({});
        });
    }
 }]);

这是我试图在我的视图函数中访问的内容:-

card.content =request.POST.get('content')

card 是我模型的对象,但我收到 NameError: name 'content' is not defined,请帮帮我!

【问题讨论】:

    标签: javascript angularjs django django-views


    【解决方案1】:

    你可以尝试在没有 jquery 参数的情况下使用吗?尝试在 $http.post(url, data, config) 中传递简单对象

        var nameSpace = angular.module("ajax", ['ngCookies']);
    
    nameSpace.controller("MyFormCtrl", ['$scope', '$http', '$cookies',
    function ($scope, $http, $cookies) {
        $http.defaults.headers.post['Content-Type'] = 'application/json';
        // To send the csrf code.
        $http.defaults.headers.post['X-CSRFToken'] = $cookies.get('csrftoken');
    
        // This function is called when the form is submitted.
        $scope.submit = function ($event) {
            // Prevent page reload.
            $event.preventDefault();
            // Send the data.
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }
            var in_data = {content: $scope.card.content,csrfmiddlewaretoken: $cookies.csrftoken};
            $http.post('add_card/', in_data, config)
              .then(function(json) {
                // Reset the form in case of success.
                console.log(json.data);
                $scope.card = angular.copy({});
            });
        }
     }]);
    

    【讨论】:

    • 我也应该改变我的views.py吗??@agam
    • @VinitRaj 无需更改 view.py 文件
    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 2019-08-25
    • 2012-01-17
    • 2017-12-13
    • 2021-03-17
    相关资源
    最近更新 更多