How to send json serialize data from a form to ajax using django

前端 未结 2 1282
小蘑菇
小蘑菇 2021-01-07 15:20

Currently, I\'m sending the data via code in this way and it\'s working but how can I send the entire form in json?

Code :

 $.ajax({
         url : w         


        
相关标签:
2条回答
  • 2021-01-07 15:42

    You could grab the form data usingserializeArray function in jQuery, then convert it into dictionary and send as post data.

    The serializeArray function output would be something like,

    { 
        'name': 'the_name',
        'value': 'the_value'
    }
    

    Then, you would have to convert it to the dictionary or json format. Write a global function for that,

    function objectifyForm(formArray) {
        var returnArray = {};
        for (var i=0;i<formArray.length;i++) {
            if (formArray[i].value) {
                returnArray[formArray[i].name] = formArray[i].value;
            }
        }
        return returnArray;
    }
    

    Call it whenever you have to grab the form data,

    var formData = $('#my_form').serializeArray();
    formData = objectifyForm(formData);
    $.ajax({ 
            url : window.location.href, // the endpoint,commonly same url 
            type : "POST", // http method
            data : formData, 
            success: blaah,
            error: bleeh,
        });
    

    It would be much less effort than having to decode the dictionary every time from the server side.

    0 讨论(0)
  • 2021-01-07 16:05

    you need to send json serialized form data as one paramater and csrf token as another parameter because every POST request expects a csrf token in it.

        csrfmiddlewaretoken = $("#add_member_Form").find("input[name='csrfmiddlewaretoken']" ).val();
        formData = $('#add_member_Form').serializeArray();
        formData = JSON.stringify(formData);
        $.ajax({
            url : url,
            data : {
                "csrfmiddlewaretoken" : csrfmiddlewaretoken,
                "formData" : formData
            },
            method: "POST",
            dataType : "json",
    

    At server side in your view, you need to deserialize the data.

    form_data_dict = {}
    form_data_list = json.loads(form_data)
    for field in form_data_list:
        form_data_dict[field["name"]] = field["value"]
    return form_data_dict
    
    0 讨论(0)
提交回复
热议问题