【问题标题】:How to access data sent in ajax call in views.py python djangopython - 如何在views.py中访问在ajax调用中发送的数据
【发布时间】:2014-06-05 11:53:28
【问题描述】:

下面是我在 html 中用来发送用户 ID(数字)数组的代码。单击复选框时,我将发送数组(checkIds):-

var checkIds = []
           $(document).on("click","#group_save",function(){
               $("#candidate-data tr").each(function(index,rowhtml){
                  var checked= $('input[id="groups"]:checked',rowhtml).length;
                  checkIds = jQuery.unique(checkIds)
                  if (checked==1){
                    checkIds.push($('.hideMe',rowhtml).text());
                  }
                });
               alert(checkIds);
               var jsonText = JSON.stringify(checkIds)
               checkIds.length = 0;
               var groupName = $('input:text[name="group_name"]').val();
               alert(groupName)
               $.ajax({
                    url: "{% url 'userinfo:groups' %}" + "?gname="+groupName,
                    type: "POST",
                    data:jsonText,
                    dataType: 'json',
                    success: function(){
                        notyfy({type: "success", layout: "topCenter", text: "Saved", timeout: 5000});
                    }
               });
           });

如何在我的视图中访问data:jsonText。 py 我这样做是行不通的 我必须将gname(name) 和数组(jsonText) ids 保存在两个表Groups 和GroupMembers 中的groups 表中我必须保存组名(gname) 和保存后,我必须获取已保存组对象的 id,并且必须将 userids(jsonText) 数组保存在 GroupMembers 表中:-

def groups(request):
    gname = request.GET.get('gname', None)
    if request.method == 'POST':
        Groups(name=gname).save()
        usersV = request.POST.get('jsonText')
        x = request.GET.get('id',None)
        print x
        if x != "0":
            for users in usersV:
                print users
                GroupMembers(group_id=x,user_id=users).save()
        return HttpResponse("Success")
    else:
        return HttpResponse("Error")

【问题讨论】:

    标签: jquery python ajax django


    【解决方案1】:

    这对我有用:

     var checkIds = [];
            $(document).on("click","#group_save",function(){
              $("#candidate-data tr").each(function(index,rowhtml){
                var checked= $('input[id="groups"]:checked',rowhtml).length;
                checkIds = jQuery.unique(checkIds)
                if (checked==1){
                  checkIds.push($('.hideMe',rowhtml).text());
                }
              });
              alert(checkIds);
              var groupName = $('input:text[name="group_name"]').val();
              alert(groupName);
                $.ajax({
                    url: "{% url 'userinfo:groups' %}" + "?gname="+groupName+"&checkids="+checkIds,
                    type: "POST",
                    dataType: 'json',
                    traditional: true,
                    success: function(){
                            notyfy({type: "success", layout: "topCenter", text: "Saved", timeout: 5000});
                        }
                });
                checkIds.length = 0;
    

    在您的 views.py 中:

    def groups(request):
        print request.GET.copy()
        gname = request.GET.get('gname', None)
        if request.method == 'POST':
            g = Groups(name=gname)
            g.save()
            x = g.pk
            userlist = request.GET.get('checkids')
            for users in userlist:
                print users
                GroupMembers(group_id=x, user_id=users).save()
            return HttpResponse("Success")
        else:
            return HttpResponse("Error")
    

    【讨论】:

      【解决方案2】:

      您应该能够使用以下内容:

      var checkIds = [];
      $(document).on("click","#group_save",function(){
        $("#candidate-data tr").each(function(index,rowhtml){
          var checked= $('input[id="groups"]:checked',rowhtml).length;
          checkIds = jQuery.unique(checkIds)
          if (checked==1){
            checkIds.push($('.hideMe',rowhtml).text());
          }
        });
        var groupName = $('input:text[name="group_name"]').val();
        $.ajax({
          url: "{% url 'userinfo:groups' %}",
          type: "POST",
          data: {
            "gname": gname,
            "checkids": checkIds.slice(0)
          },
          dataType: 'json',
          traditional: true,
          success: function(){
            notyfy({
              type: "success", 
              layout: "topCenter", 
              text: "Saved", 
              timeout: 5000
            });
          }
        });
        checkIds.length = 0;
      });
      

      然后在你的 python 端使用:

      request.POST.get('gname');
      request.POST.getlist('checkids');
      


      简短说明

      首先,jQuery 会为您处理数据对象的转换,因此无需使用JSON.stringify 或其他任何东西对其进行预处理,除非您向服务器发送非常特定的格式。通过设置traditional: true,您要求 jQuery 使用以下格式转换您的数组参数:

      checkids=value&checkids=value&checkids=value
      

      而不是:

      checkids[]=value&checkids[]=value&checkids[]=value
      

      herehere 对此进行了很好的解释,但总而言之,python/django 使用 .getlist() 支持开箱即用的“非方括号”形式的参数序列化。

      哦,checkIds.slice(0)(创建数组的副本)的原因只是因为您稍后设置了checkIds.length = 0;,而我脑海中的妄想症告诉我,如果 ajax 调用在以后的执行中触发如果我使用直接引用而不是副本,则循环数组将为空。这是极不可能的,因为应该在请求它的那一刻触发 ajax 调用,但是在处理黑盒或 jQuery 之类的库时,我总是会谨慎行事......虽然你不应该迎合我的偏执狂并且很可能可以安全地使用:

          data: {
            "gname": gname,
            "checkids": checkIds
          },
      

      【讨论】:

      • 但它显示 checkIds 长度为零,数组中没有元素。请帮助我谢谢 Pebbl
      • @user3710945 ~ 它在哪里显示checkIds 长度为零?是在ajax调用之前吗?还是在 django/python 方面?如果是在 ajax 调用之前,那么我们需要调查您的 jQuery 以收集 checkId,如果在 Django 端,您需要使用 checkids 全部小写(至少就我上面的回答而言)。显然,如果您在 ajax 调用之后进行检查,checkIds.length = 0 将是问题所在。
      • 当我在 pycharm 中调试代码时,它在 django python 端我发现 checkids 长度为零,即使我删除了行 checkids.length = 0;
      • @user3710945 ~ 如果您使用def groupsdef groups 顶部使用的最新代码更新您的问题,请添加print request.GET.copy() 并将该输出添加到您的问题中帮助调试问题。
      【解决方案3】:

      jsonText是你在js文件中用来描述JSON的变量名。它不是 JSON 结构中某些数据的键名。在下面的行中,将 jsonText 替换为实际的密钥名称。

      request.POST.get('jsonText')
      

      【讨论】:

        【解决方案4】:

        request.POST 字典用于表单编码值。你不是在发送那些:你是在发送一个 JSON blob。您可以使用request.body 获取该 JSON,然后对其进行解析以获取 Python 字典。

        usersV = json.loads(request.body)
        

        【讨论】:

          猜你喜欢
          • 2020-10-08
          • 1970-01-01
          • 2011-08-12
          • 2018-02-13
          • 2012-11-08
          • 1970-01-01
          • 1970-01-01
          • 2015-02-04
          • 2021-10-18
          相关资源
          最近更新 更多