Django + Angular : how to send angularjs $http data or params to django and interpret in django?

标签 django angularjs

为什么我不能使用 $http 的参数或数据来与 Django 通信?

我有一个 angularjs 页面,它从 django View 获取数据。在一种情况下,我有一个名为/display 的 django View ,它从服务器获取文件并将其显示为纯文本。

this.loadfile = function (clickedItem) {
    $http({method: 'GET' , url: '/display/'+ clickedItem.fileName})
        .success(function(data) {
                $scope.fileView.text = data;

        });
};

对/display/myfile.txt 的调用效果很好,因为文件名是一个简单的字符串,返回的数据也是如此。

现在我需要向 django 发送一个更复杂的多行参数:搜索字符串列表和文件名列表:

  this.concord = function (searchStrings, filenames) {

        $http({method: 'GET' ,
                url: '/concord/',
                data: {"searchStrings":searchStrings, "filenames":filenames}
            )
            .success(function(data) {
                console.log(data); // log the data coming back.
                $scope.concord = data;
            });
    };

根据AngularJS - Any way for $http.post to send request parameters instead of JSON? ,应该适用于

url(r'^concord/(?P<jsondata>.*)$', views.concord, name="concord"),

我的观点是:

def concord(request,jsondata) :
    jObj=simplejson.loads(jsondata)
    return HttpResponse(jObj["files"])

(我也尝试解析 request.body;为空)

另一方面,如果我明确地将其附加到 URL,我确实会得到一些结果:

 $http({method: 'GET',
                url: '/concord/'+JSON.stringify({"searchStrings":searchStrings, "filenames":filenames}),

            }
            )
            .success(function(data) {
                console.log(data);
                $scope.concordResults = data;
            });

这有效!

但我必须以最糟糕的方式来做这件事。有没有办法使用参数或数据与 Django 进行通信?

(PS:我已经避免使用 django-Angular 包,因为我已经对学习包感到不知所措:django Rest、Angular、Bootstrap 等......我真的只想从 Angular 和 Django 之间的基本通信开始。稍后我将深入研究更多包。)

最佳答案

如果您查看 angularjs 文档 (https://docs.angularjs.org/api/ng/service/ $http),您会发现您可以在您的案例中获取参数并发布 json 等数据。

当您发帖时,您将执行以下操作:

$http.post('http://www.example.com/post_data_url',
           { 'key': $scope.value }
          );

在 django 端,不要向 URL 添加任何参数,JSON 将位于请求内部,更准确地说是在正文中:

import json

def concord(request):
  dictionary = json.loads(request.body)
  # to use the value, access the created dictionary
  print dictionary['key']
  [...]

关于 Django + Angular : how to send angularjs $http data or params to django and interpret in django?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24766479/

相关文章:

python - 如何检查列表中的当前用户是否投票了某个帖子

Django TokenAuthentication - 扩展 JWT obtain_jwt_token

AngularJS : Where to use promises?

java - 如何将多个对象从 Angular2 发送到 Java Spring 后端

javascript - PHP 获取呈现的 Javascript 页面

python - 带整数的 Solr Facet 范围

django - 如何在构建时链接 docker 容器?

python - Django 模型序列化器

javascript - AngularJS - ng-click 在模态中不起作用

javascript - Angular $http.get 自动将 int 转换为 string