首页 > 解决方案 > 将参数从js传递给django

问题描述

我在views.py中有一个函数

def time(request): 
    date = Registration.objects.filter(date_visit=date_use)
    time_list=[]
    for a in date:
        time_list.append(date.time_visit)
    return JsonResponse({'time_list':time_list})

我想从表单中的字段中传递 date_use 参数。

我这样计算字段值

$(document).ready(function() {
  $('.pole').change('input', function() {
     var val = $(this).val();
  });
});

如何将 val 值传递给 date_use?

标签: javascriptdjango

解决方案


您可以使用dataJSajax请求中的键在两者中传递参数getpost请求。

注意 - 使用 Django 提交表单时,您需要获取csrf token并将其设置为X-CSRFToken标题。您可以在此处使用 Django Docs 本身提供的以下代码。

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
  $('.pole').change('input', function() {
     var datetime = $(this).val();
     var cookie = getCookie('csrftoken')
       $.ajax({
           url: '/your-url/',
           headers: {'X-CSRFToken': cookie},
           type: 'get', // can be 'post' as well or anything else you'd want such as 'put', 'patch', etc'
           data: {'datetime': datetime},
           success: function(e){
             console.log(e)
           },
           error: function(e){
                console.log(e);
           }
       })    
  });

视图.py

def time(request): 
    if request.method == "GET":
        date = Registration.objects.filter(date_visit=date_use)
        # you can get the value from the JS using the `key` in `data` attribute of `ajax request`
        data_from_form = request.GET.get('datetime')

        # if you have multiple inputs coming your way for example if there's a list of inputs you're getting you can use 
        data_from_form = request.GET.getlist('datetime')
        time_list=[]
        for a in date:
            time_list.append(date.time_visit)
        return JsonResponse({'time_list':time_list})

注意 - 您可能需要ajax request在多个页面中使用,并且在每个页面中复制和粘贴该getCookie功能会适得其反。相反,您可以做的是将此代码粘贴到一个名为的新文件utils.js中,然后将此文件导入您的base.html. 请记住,导入定位为utils.js. 如果您需要将其中的函数使用到另一个脚本中,则需要在下面导入该特定脚本utils.js

base.html

{% load static %}
<html>
<head>
</head>
<body>

<script src="{% static '/js/utils.js' %}" type='text/javascript'></script>
</body>
</html>

推荐阅读