简体   繁体   English

将值从 JavaScript 传递到 Django

[英]Passing Values from JavaScript to Django

I have three forms like this:我有三个像这样的 forms:

<form  id = "myForm" style="list-style-type: none;display: none;" class="form_class">
                {% csrf_token  %}
                    item1:
                    <input type="text" name="item1" style="width:10%;height:5%"> 
                    <br>
                    item2:
                    <input type="text" name="item2" style="width:10%;height: 5%">
                    <br>
                    item2:
                    <input type="text" name="item2" style="width:10%;height: 5%">
                    <br>
                    item2:
                    <input type="text" name="item2" style="width:10%;height: 5%">
                    <br>
                    item2:
                    <input type="text" name="item2" style="width:10%;height: 5%"> 
                    
                    <br><br> 
                    <input id="close_form" type="reset" value="reset">
                </form>      

Below is the code I used to click the button so it will go the javascript method:下面是我用来单击按钮的代码,因此它将 go javascript 方法:

 <form method="post">
   {% csrf_token %}
   <input class="bg-yellow text-white" value="RUN" name="runModel" type="submit" 
   onclick="sendValuesToBack()">
 </form>
                

In the JavaScript method, I'm getting all three form's values.在 JavaScript 方法中,我得到了所有三个表单的值。 I want to send those to the Django Framework to perform several operations.我想将这些发送到 Django 框架以执行多项操作。 How do I send this data from JavaScript to Django?如何将此数据从 JavaScript 发送到 Django?

You can do this using JQuery Ajax in the template and by creating an "API view" in your views.py that is basically just a regular view that returns a JSONResponse after checking to verify the request is Ajax.您可以在模板中使用 JQuery Ajax 并在您的 views.py 中创建一个“API 视图”,该视图基本上只是一个常规视图,在检查以验证请求是否为JSONResponse后返回 JSONResponse As an example of the "API" option, using JQuery:作为“API”选项的示例,使用 JQuery:

In your urls.py:在您的 urls.py 中:

...
path('/api/post_form/', post_form_api, name="post_form_api"),
...

For the POST method in your views.py:对于您的 views.py 中的 POST 方法:

        from django.http import JsonResponse

        def post_form_api(request):
              data = {}
              if request.method == "POST":
                  form = MyDjangoForm(request.POST)
                  # do something with the form data
                  ...
                  if successful:
                     data['result'] = True
                     data['message'] = "Form data saved"
              if request.is_ajax():
                 return JsonResponse(data)
              else:
                 return HttpResponseBadRequest()

In your template:在您的模板中:

<script type="text/javascript">
        $("#myFormSubmitButton").click(function(){
                var form_data = $("#formID").serialize();
                $.ajax({ url: '{% url 'post_form_api' %}',
                                    type: "POST",
                                    dataType: "json",
                                    data: form_data,
                                    cache: false
                           }).done(function(data) {
                                if (data.result === true){
                                    alert(data.message);
                               }
                           });
                      });
                  });
            </script>

Alternatively, you can get the fields from all your forms individually, then send them in the Ajax data like so:或者,您可以单独从所有 forms 中获取字段,然后将它们发送到 Ajax 数据中,如下所示:

<script type="text/javascript">
        $("#myFormSubmitButton").click(function(){
            var csrfToken = $("input[name='csrfmiddlewaretoken']");
            var item_1 = $("#item1").val();
            var item_2 = $("#item2").val();
            ...
                $.ajax({ url: '{% url 'post_form_api' %}',
                                    type: "POST",
                                    dataType: "json",
                                    data: {'item1': item_1, 'item2': item_2, 'csrfmiddlewaretoken':csrfToken.val()},
                                    cache: false
                           }).done(function(data) {
                                if (data.result === true){
                                    alert(data.message);
                               }
                           });
                      });
                  });
            </script>

If you have multiple forms you want to use this API for and are only submitting them one at a time, you can put a hidden field in your forms and do something like this in your views.py:如果您有多个 forms 想要使用此 API 并且一次只提交一个,您可以在 forms 中放置一个隐藏字段并在您的视图中执行类似的操作。py:

     def post_form_api(request):
          data = {}
          if request.method == "POST":
              form_name = request.POST.get('form_name', None) #the name of the hidden field identifying the form
              if form_name is not None:
                  if form_name == "MyDjangoForm":
                      form = MyDjangoForm(request.POST)
                      # do something with the form data
                      ...
                  elif form_name == "MyOtherForm":
                      form = MyOtherForm(request.POST)
                      # do something with the form data
                      ...

              if successful:
                 data['result'] = True
                 data['message'] = "Form data saved"

          if request.is_ajax():
             return JsonResponse(data)
          else:
             return HttpResponseBadRequest()

If you are getting the data from all three forms in your template at once, you can do something like this in your views.py after sending all of the data using JQuery Ajax as above:如果您同时从模板中的所有三个 forms 获取数据,您可以在使用 JQuery Ajax 发送所有数据后在您的views.py中执行类似的操作:

     def post_form_api(request):
          data = {}
          if request.method == "POST":
              item_1 = request.POST.get('item_1', None)
              item_2 = request.POST.get('item_2', None)
              item_3 = request.POST.get('item_3', None)
              ...
              # do something with the collected form data here
              ...

              if successful:
                 data['result'] = True
                 data['message'] = "Form data saved"

          if request.is_ajax():
             return JsonResponse(data)
          else:
             return HttpResponseBadRequest()

When you are sending data via POST don't forget to pass along your CSRF token as in the example above (it should be in the serialized form data).当您通过 POST 发送数据时,请不要忘记传递您的 CSRF 令牌,如上例所示(它应该在序列化表单数据中)。 This assumes you have a form on the page you can get it from, otherwise you can use something like this to get it:这假设您在页面上有一个可以从中获取它的表单,否则您可以使用类似这样的东西来获取它:

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;
}
var csrftoken = getCookie('csrftoken');

If you don't want to deal with the CSRF token, you can mark the view with the @csrf_exempt decorator and remove the ' csrfmiddlewaretoken ' data element from the Ajax call in the template, but it may not be ideal or the most secure.如果您不想处理 CSRF 令牌,您可以使用@csrf_exempt装饰器标记视图并从模板中的 Ajax 调用中删除“ csrfmiddlewaretoken ”数据元素,但这可能不是理想的或最安全的。 An example of that:一个例子:

    from django.views.decorators.csrf import csrf_exempt
    from django.http import JsonResponse

    @csrf_exempt()
    def post_form_api(request):
           ...

Now, without knowing more, this is basically just pseudocode (plus I just wrote this off the top of my head so it may have errors).现在,在不了解更多信息的情况下,这基本上只是伪代码(另外我只是在脑海中写下了这个,所以它可能有错误)。 This also depends on what type of views you are using, and whether you want to use the Django REST framework or not (the examples above are for regular, not class-based, views and do not require the Django REST framework to work). This also depends on what type of views you are using, and whether you want to use the Django REST framework or not (the examples above are for regular, not class-based, views and do not require the Django REST framework to work).

If you post more details I can update my answer, but I think this should get you started.如果您发布更多详细信息,我可以更新我的答案,但我认为这应该让您开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM