Django + jQuery get data in the form + Ajax send data

1. Method 1: obtain form data through Jquery$("# corresponding form id). SerializeArray (), and directly assign values to $. Ajax data.

.serializearray () method see jQuery ajax-serializearray () method
this method puts back an array of JSON objects.

$("#postSubmit").click(function () {
                    let data = $("#postContent").serializeArray();
                    $.ajax({
                        url: '/decuhub/home-post-ajax',
                        method: 'POST',
                        data: data,
                        async: true,
                        success: function (result) {
                            console.log("post successfully!")
                        }
                    })
                })

2. The method 2: by $(" # corresponding form form id) serializer () to obtain the form data:

$("#postSubmit").click(function () {
                    let data = $("#postContent").serializer();
                    $.ajax({
                        url: '/decuhub/home-post-ajax',
                        method: 'POST',
                        data: data,
                        async: true,
                        success: function (result) {
                            console.log("post successfully!")
                        }
                    })
                })

. Method 3:

is not recommended

$("#postSubmit").click(function () {
                    let postContentForm = $("#postContent").serializeArray();
                    let data = {};
                    $.each(postContentForm, function(){
                        data[this.name] = this.value;
                    })
                    $.ajax({
                        url: '/decuhub/home-post-ajax',
                        method: 'POST',
                        data: data,
                        async: true,
                        success: function (result) {
                            console.log("post successfully!")
                        }
                    })
                })

$.each() reference jQuery. Each ()

Django's request-post gets

<QueryDict: {'csrfmiddlewaretoken': ['vO34OFZtTj2Bp2ARMlXVJxZQb37CyuWR7ywaDC4QaJhHtcxB4xB9fnb2IOnbQ2AR'], 'content': ['asdfsd']}>


Read More: