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

前端 未结 2 1284
小蘑菇
小蘑菇 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 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
    

提交回复
热议问题