Django表单使用Ajax Javascript提交

时间:2019-05-29 07:43:53

标签: javascript ajax django django-forms ajaxform

我正在尝试从输入数据网格表中发布表单。当我打印filter_list(请参阅代码)时,我只会得到一个None对象。但是当我成功使用 alert 函数从表中检查数据时,它将返回正确的选定值。对ajax了解很多。 请帮我弄清楚。我在下面附加了views.py,HTML的代码, 在Views.py中,

def mytable1(request):
    if request.method == 'POST':
        filter_list = request.POST.get('regionwiselist')
        **print(filter_list)**
        context={'filter_list':filter_list}
        print(context)
        return render(request, 'mytable2.html', context)
    else:
        sbc = MTD.pdobjects.all()
        df = sbc.to_dataframe().reset_index(drop=True)
        df.reset_index(inplace=True)
        dict1=df.transpose().to_dict()
        dict=[]
        for k,v in dict1.items():
            dict.append(v)
        col=list(df1.columns)
        context={
                'Vertical_value':dict,
                'Vertical_header':col
        }
        return render(request, 'mytable2.html', context)

在mytable2.html中

{% extends "base.html" %}
{% block body %}
{% if Vertical_header  %}
<script>
  $(document).ready(function(){
    $("#gridContainer").dxDataGrid({
        dataSource: {{Vertical_value|safe}},
        showBorders: true,
        paging: {
            pageSize: 10
        },
        keyExpr: "RGN",
        showBorders: true,
        selection: {
            mode: "multiple"
        },
        paging: {
            pageSize: 10
        },
        filterRow: {
            visible: true
        },
        pager: {
            showPageSizeSelector: true,
            allowedPageSizes: [5, 10, 20],
            showInfo: true
        },
        columns: {{Vertical_header|safe}},
        showBorders: true
    });
  });
</script>
<div class="demo-container">
  <form id='my_form' method = "POST">
    {% csrf_token %}
      <div id="gridContainer"></div>
      <button type="submit" class="btn btn-primary btn-lg"><i class="fa fa-angle-double-down"></i></button>
  </form>
</div>
<script type="text/javascript">
  $(document).on('submit','#my_form',function data(e){
    var dataGrid = $("#gridContainer").dxDataGrid("instance");
    var selectedKeys = dataGrid.getSelectedRowKeys();
    $.ajax({
        type: 'POST',
        url: '{% url 'mytable1' %}',
        data:{
          regionwiselist:selectedKeys[0].value,
          csrfmiddlewaretoken:$("[name=csrfmiddlewaretoken]").val()
        },
        success: function(){
            alert(selectedKeys);
          }
       });
});
</script>
<script type="text/javascript">
  function data(){
    var dataGrid = $("#gridContainer").dxDataGrid("instance");
    var selectedKeys = dataGrid.getSelectedRowKeys();
    console.log(selectedKeys[0])
  };
</script>
<button onclick="data()" type="button" name="button"></button>
{% else %}
<h2>kd:{{filter_list|safe}}</h2>

{% endif %}

{% endblock %}

0 个答案:

没有答案