javascript 提交ajax django表格

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 提交ajax django表格相关的知识,希望对你有一定的参考价值。

//Instructions

1. Add the idForm id to your form
2. Add this script at the bottom of your body. Remember to use the {% block footer_scripts %} block in your main
template if you are extending your template and add this script in this block.
3. That's all, enjoy your form submission through Ajax!

<script>

        $body = $("body");
        //AjaxStart and AjaxStop  
        $(document).ajaxStart(
            function() {
                alert("starting")
                $body.addClass("loading");

            }
        );
        $(document).ajaxStop(
            function() {
                alert("Stopping")
                $body.removeClass("loading");
            }
        );

        /*
        $(document).on({
            ajaxStart: function() { $body.addClass("loading");    },
             ajaxStop: function() { $body.removeClass("loading"); }
        }); */
        
        
        //We configure CSRF needed by the Django Validation System
        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 = jQuery.trim(cookies[i]);
                    // 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');

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        $.ajaxSetup({  //Finally, setting up AJAX
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });
        
        //Django Function Useful to submit a form
        $(function() {
          alert("hello world")
          $('#idForm').submit(function(event) { //Specifying the form with id #idForm
            console.log("Hello, i'm here!")
            event.preventDefault(); // Prevent the form from submitting via the browser
            var form = $(this);  //Getting the form
            var formData = new FormData(form.get(0)); //appending the form as a FormData object

            $.ajax({  //Executing the Ajax. processData, cache, and contentType needed, i don't know why
              processData: false,
              type: form.attr('method'),
              url: form.attr('action'),
              data: formData,
              cache: false,
              contentType: false,

            }).done(function(data) {   //When finished, load some div with id trying
                alert("Très bien")
                $('#trying').html(data)
              // Optionally alert the user of success here...
            }).fail(function(data) {  //When finished, if there is a failure, do something
              // Optionally alert the user of an error here...
                alert("Fail")
            });
          });
        });
        </script>

以上是关于javascript 提交ajax django表格的主要内容,如果未能解决你的问题,请参考以下文章

上传文件后,如何在 Django 中使用 AJAX 更新表(与 JavaScript 链接)?

Django富文本编辑和ajax提交评论

Django 表单未使用 Javascript 提交

Django AJAX方式提交数据解决csrf验证问题

Django AJAX方式提交数据解决csrf验证问题

在javascript-ajax中提交表单时如何显示进度条