how to use ajax function to send form without page getting refreshed, what am I missing?Do I have to use rest-framework for this?

后端 未结 11 2252
花落未央
花落未央 2021-01-05 03:37

I\'m trying to send my comment form using ajax, right now when user inserts a comment then whole page gets refreshed. I want this to be inserted nicely without page getting

11条回答
  •  长情又很酷
    2021-01-05 04:20

    This is the easiest example of how to implement Ajax forms in conjunction with Django:

    You can use Ajax Post to send JSON to Django and then handle the arguments as a dict(). Here is an example:

    In browser (JQuery/JavaScript):

        function newModule() {
    
            var my_data = $("#my_element").val(); // Whatever value you want to be sent.
    
            $.ajax({
                url: "{% url 'modules' %}",       // Handler as defined in Django URLs. 
                type: "POST",                     // Method.
                dataType: "json",                 // Format as JSON (Default).
                data: {
                    path: my_data,                // Dictionary key (JSON). 
                    csrfmiddlewaretoken: 
                             '{{ csrf_token }}'   // Unique key.
                },
    
                success: function (json) {
    
                    // On success do this.
    
                },
    
                error: function (xhr, errmsg, err) {
    
                    // On failure do this. 
    
                }
    
            });
    

    In server engine (Python):

    def handle(request):
    
        # Post request containing the key.  
        if request.method == 'POST' and 'my_data' in request.POST.keys():
    
            # Retrieving the value.
            my_data = request.POST['my_data']
    
        # ...
    

提交回复
热议问题