簡體   English   中英

使用ajax一次將包含JavaScript的頁面上的所有表單提交給Django

[英]Submitting all forms on a page with JavaScript using ajax at once to Django

我有一個包含多種形式的頁面,該頁面的ID附有GUID。 我是通過合並堆棧帖子來編寫此JavaScript的。 我的JavaScript並不是那么出色。

當我提交表單時,一些表單文本框消失了,並且傳遞給django的數據沒有發布值。 如果我立即記錄表單,然后再使用console.log(formData[0]);將其發送給使用ajax序列化的表單console.log(formData[0]); 它記錄表單數據和所有元素。

當我打印出帖子值,並使用django將帖子值返回到頁面時,它完全空白。 提交的內容沒有序列化表格。 我認為這是因為它們以附加到主要生成的表單frmCollector的表單數組的形式存在。 當我將其null提交給django時。 如何合並所有表單並使用ajax提交作為對象發送到django。 我會建立一個json對象。 表單具有唯一的uuid,所以我不知道它們是什么。 我可以建立一個清單,但是我敢肯定有一種更有效的方法可以在javascript中做到這一點。

這是到目前為止的完整腳本代碼:

<script>
    function submitAllDocumentForms() {
        var alldata = {};

        $("form").each(function(i, form){

          var current_data = $(form).serializeArray();
          console.log($(form).serializeArray());  
          alldata[$(form).prop("id")]  = current_data;

        });

        alert(JSON.stringify(alldata));

        $.ajax({
          type:'POST',
          url:'save_stacks/',
          data: JSON.stringify(alldata),
          success: function(response) {
           console.log(response);
          }
        });
    }

        var stack_name = "";
        var stack_id_out = "";
        var globalWidth = "";

        var stacksHash = {};

        function guid() {
          function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
              .toString(16)
              .substring(1);
          }
          return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
        }

        function generate_stack_list(idobject){
            var update_list_html = "";
            $.each(stacksHash, function(i, item) {
                update_list_html += '<option value="'+stacksHash[i].stackid+'">'+stacksHash[i].stackid+'</option>';
            }); 
            var id_out = idobject.id.replace(/SecurityGroup/g, "stack_name");
            document.getElementById(id_out).innerHTML = update_list_html;
        }

        function generate_stack(id){
            var stackName = prompt("Please enter your stack name", "storm-nimbus");
            var uuid = guid();

            var id_out = id.replace(/UUID/g, uuid);
            id_out = id_out.replace(/Hide/g, "");
            id_out = id_out.replace(/StackName/g, stackName);
            //stack_ids.set("stackid", id_out);

            stacksHash[id_out]= {"stackid":id_out};
            stack_id_out = id_out;
            var rawFile = new XMLHttpRequest();

            rawFile.open("GET", "{% static 'divTemplates/stack.html' %}", false);

            rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
                {
                    if(rawFile.status === 200 || rawFile.status == 0)
                    {
                        var allText = rawFile.responseText;

                        var html_out = allText.replace(/UUID/g, uuid);  

                        var html_out_final = html_out.replace(/STACKNAME/g, id_out); 

                        var current_html = document.getElementById("dynamic_content").outerHTML;

                        document.getElementById("dynamic_content").outerHTML = html_out_final + current_html;

                        globalWidthid = "#"+uuid;
                        globalWidth = $( globalWidthid ).css( "width" );

                    }
                }
            }
            rawFile.send(null);

            //generate multiple list options and software options for the stack
            var html_anaconda_options = "";
            var second_index_position = "";
            var first_index_position = "";
            var anaconda_data = "";
            var number_of_anacondas = "";

            options_id_anaconda = "#SoftwareTab-Anaconda-"+uuid;
            options_id_anaconda_input = "#SoftwareTab-Anaconda-Search-"+uuid;
            options_id_anaconda_links = "#SoftwareTab-Anaconda-Links-"+uuid;

            $.get( "anaconda/", function( data ) {
                anaconda_data = data[0];
                var count = 0;
                $.each(data, function(index) {
                    $.each(data[index], function(index2) {
                        number_of_anacondas++;
                        count++;
                        if(count < "3000"){
                            add_html_options(data[index][index2]);
                            second_index_position = index2;
                            first_index_position = index;

                        }
                    });                 
                }); 
                set_html_anaconda_options();
            });

            function add_html_options(data){
                html_anaconda_options += "<option value='"+data.package+"-"+data.version+"'>"+data.package +"-"+ data.version +"-"+ data.os +"-"+ data.channel +"-"+"</option>";            
            }



            function set_html_anaconda_options(){
                $( options_id_anaconda ).html(html_anaconda_options);
                //console.log(anaconda_data[first_index_position][second_index_position]);
                $( options_id_anaconda_links ).html( "<p style='float:right;'>"+first_index_position + " - " + second_index_position + " of " + number_of_anacondas + "<button style='margin-left:5px;margin-top:5px;' class='btn btn-success' id='anaconda-link-next-"+uuid+"+"+second_index_position+"' onclick='next_anaconda(this)' href='#'>"+" Next "+second_index_position+"</button></p>");
            }
        }

        function next_anaconda(next_value_starting_point){

            var id_tag_information = next_value_starting_point.id.replace(/anaconda-link-next-/g, "");
            var uuid = id_tag_information.split("+")[0];
            var number_of_range = id_tag_information.split("+")[1];
            var next_max = id_tag_information.split("+")[1] * 2;

            var html_anaconda_options = "";
            var anaconda_data = "";
            var number_of_anacondas = "";
            var second_index_position = "";
            var first_index_position = "";

            $( options_id_anaconda ).html("");

            options_id_anaconda = "#SoftwareTab-Anaconda-"+uuid;
            options_id_anaconda_input = "#SoftwareTab-Anaconda-Search-"+uuid;
            options_id_anaconda_links = "#SoftwareTab-Anaconda-Links-"+uuid;

            $.get( "anaconda/", function( data ) {

                anaconda_data = data;
                var count = number_of_range;
                $.each(data, function(index) {
                    $.each(data[index], function(index2) {
                        number_of_anacondas++;
                        if ( count == index2 ){
                            count++;
                            if( count < next_max){
                                    add_html_options_update(data[index][index2]);
                                    second_index_position = count;
                                    first_index_position = next_max;
                            }
                        }
                    });                 
                }); 
                set_html_anaconda_options_update();
            }); 
            function add_html_options_update(data){
                html_anaconda_options += "<option value='"+data.package+"-"+data.version+"'>"+data.package +"-"+ data.version +"-"+ data.os +"-"+ data.channel +"-"+"</option>";            
            }
            function set_html_anaconda_options_update(){
                $( options_id_anaconda ).html(html_anaconda_options);
                var next_max_count = second_index_position *2;
                $( options_id_anaconda_links ).html("<p style='float:right;'>"+first_index_position + " - " + next_max_count + " of " + number_of_anacondas + "<button class='btn btn-success' style='margin-left:5px;margin-top:5px;' id='anaconda-link-next-"+uuid+"+"+second_index_position+"' onclick='next_anaconda(this)' href='#'>"+" Next "+second_index_position+"</button></p>");
            }

        }
        function delete_stack(id){
            var answer = prompt("Are you sure?", "yes");
            if (answer == "yes"){
                id = "#"+id;
                $( id ).remove();       
            }else{
            }
        }

        function delete_blockdevice(deviceObject){
            var answer = prompt("Are you sure?", "yes");
            if (answer == "yes"){
                var id = deviceObject.id.replace(/DB/g, "");  
                id = "#"+id;
                $( id ).remove();       
            }else{
            }

        }   
        //this is the code that generates a block device div form
        //uses 
        function generate_blockdevice(idObject){
            var bd_uuid = guid();
            var rawFile = new XMLHttpRequest();
            var stackID = idObject.id.replace(/BD/g, "");
            var contentID = "block_device_content-"+ stackID;
            rawFile.open("GET", "{% static 'divTemplates/blockdevice.html' %}", false);

            rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
                {
                    if(rawFile.status === 200 || rawFile.status == 0)
                    {
                        var bdallText = rawFile.responseText;
                        var insert_uuid = stackID + "-bd_uuid-" + bd_uuid;
                        var html_out = bdallText.replace(/BDUUID/g, insert_uuid);

                        var current_html = document.getElementById(contentID).outerHTML;

                        document.getElementById(contentID).outerHTML = html_out + current_html;
                    }
                }
            }
            rawFile.send(null);     

        }   

            //this deletes a block device
        function delete_generate_security_group(deviceObject){
            var answer = prompt("Are you sure?", "yes");
            if (answer == "yes"){
                var id = deviceObject.id.replace(/DB/g, "");  
                id = "#"+id;
                $( id ).remove();       
            }else{
            }

        }   
        //this is the code that generates a block device div form
        //uses 
        function generate_security_group(idObject){
            var sg_uuid = guid();
            var rawFile = new XMLHttpRequest();
            var stackID = idObject.id.replace(/SG/g, "");
            var contentID = "security_group_content-"+ stackID;

            rawFile.open("GET", "{% static 'divTemplates/securitygroup.html' %}", false);

            rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
                {
                    if(rawFile.status === 200 || rawFile.status == 0)
                    {
                        var sgallText = rawFile.responseText;
                        var insert_uuid = stackID + "-sg_uuid-" + sg_uuid;
                        var html_out = sgallText.replace(/SGUUID/g, insert_uuid);  
                        var current_html = document.getElementById(contentID).outerHTML;
                        document.getElementById(contentID).outerHTML = html_out + current_html;
                    }
                }
            }
            rawFile.send(null);     

        }       


        function generate_envvar(idObject){
            var ev_uuid = guid();
            var rawFile = new XMLHttpRequest();
            var stackID = idObject.id.replace(/EV/g, "");
            var contentID = "evn-variable-data-"+ stackID;

            rawFile.open("GET", "{% static 'divTemplates/envvar.html' %}", false);

            rawFile.onreadystatechange = function ()
            {
                if(rawFile.readyState === 4)
                {
                    if(rawFile.status === 200 || rawFile.status == 0)
                    {
                        var evallText = rawFile.responseText;
                        var insert_uuid = stackID + "-ev_uuid-" + ev_uuid;
                        var html_out = evallText.replace(/EVUUID/g, insert_uuid);  
                        var current_html = document.getElementById(contentID).outerHTML;
                        document.getElementById(contentID).outerHTML = html_out + current_html;
                    }
                }
            }
            rawFile.send(null);     

        }   


        function disable_tab(passed){

            var id = passed.id.replace(/link-/g, "");

            var pres_id1 = "#"+"presentation1-"+id;
            var pres_id2 = "#"+"presentation2-"+id;
            var pres_id3 = "#"+"presentation3-"+id;
            var pres_id4 = "#"+"presentation4-"+id;
            var pres_id5 = "#"+"presentation5-"+id;
            var pres_id6 = "#"+"presentation6-"+id;
            var pres_id7 = "#"+"presentation7-"+id;
            var pres_id8 = "#"+"presentation8-"+id;
            var pres_id9 = "#"+"presentation9-"+id;
            var pres_id10 = "#"+"presentation10-"+id;
            var pres_id11 = "#"+"presentation11-"+id;
            var pres_id12 = "#"+"presentation12-"+id;
            var pres_id13 = "#"+"presentation13-"+id;
            var pres_id14 = "#"+"presentation14-"+id;

            var main_id = "#"+id;
            var link_id = "#linl-"+id;
            var finalId = "#contentPane-" + id;
            var width=$( main_id ).css( "width" );

            console.log(main_id);

            console.log(width);
            console.log(globalWidth);
            if( width==globalWidth ){
                $( main_id ).css( "width", "600px");
                $( link_id ).css( "background-color", "#FFF");


            }

            if( width=="600px"){
                $( main_id ).css( "width", globalWidth );
                $( link_id ).css( "background-color", "#FFF");
            }

            $(pres_id1).fadeToggle( "fast", function() {}); 
            $(pres_id2).fadeToggle( "fast", function() {}); 
            $(pres_id3).fadeToggle( "fast", function() {}); 
            $(pres_id4).fadeToggle( "fast", function() {}); 
            $(pres_id5).fadeToggle( "fast", function() {}); 
            $(pres_id6).fadeToggle( "fast", function() {}); 
            $(pres_id7).fadeToggle( "fast", function() {}); 
            $(pres_id8).fadeToggle( "fast", function() {}); 
            $(pres_id9).fadeToggle( "fast", function() {}); 
            $(pres_id10).fadeToggle( "fast", function() {});    
            $(pres_id11).fadeToggle( "fast", function() {});    
            $(pres_id12).fadeToggle( "fast", function() {});    
            $(pres_id13).fadeToggle( "fast", function() {});    
            $(pres_id14).fadeToggle( "fast", function() {});        
            $(finalId).fadeToggle( "fast", function() {});      

        }
    </script>

這是已加載的動態html的示例

<div style="width:98%;padding:15px;margin-left:15px;margin-top:15px;margin-bottom:15px;position:relative;background-color:#FFF;border-radius:15px;" id="UUID">
<span class="glyphicon glyphicon-eye-open" style="color: #00db92;float:left;margin-right:5px;margin-top:5px;font-size: 35px;" aria-hidden="true"></span>

<ul class="nav nav-tabs" role="tablist">
<li id="presentation1-UUID" role="presentation">
<a id="presentation2-UUID" href="#AutoScalingGroup-UUID" aria-controls="AutoScalingGroup-UUID" role="tab" data-toggle="tab">Auto Scaling Group</a></li>
<li id="presentation3-UUID" role="presentation">
<a id="presentation4-UUID" href="#LaunchConfigTab-UUID" aria-controls="LaunchConfigTab-UUID" role="tab" data-toggle="tab">Launch Config</a></li>
<li id="presentation5-UUID" role="presentation">
<a id="presentation6-UUID" href="#UserDataTab-UUID" aria-controls="UserDataTab-UUID" role="tab" data-toggle="tab">User Data</a></li>
<li id="presentation7-UUID" role="presentation">
<a id="presentation8-UUID" href="#BlockDevicesTab-UUID" aria-controls="BlockDevicesTab-UUID" role="tab" data-toggle="tab">Block Devices</a></li>
<li id="presentation9-UUID" role="presentation">
<a id="presentation10-UUID" href="#SecurityGroupsTab-UUID" aria-controls="SecurityGroupsTab-UUID" role="tab" data-toggle="tab">FStack Connections</a></li>
<li id="presentation11-UUID" role="presentation">
<a id="presentation12-UUID" href="#SoftwareTab-UUID" aria-controls="SoftwareTab-UUID" role="tab" data-toggle="tab">Software</a>
</li>
<li id="presentation13-UUID" role="presentation">
<a id="presentation14-UUID" href="#Administration-UUID" aria-controls="Administration-UUID" role="tab" data-toggle="tab">Administration</a>
</li>
<li id="hide-UUID" role="presentation">
<a href="#" id="link-UUID" onclick="disable_tab(this);" data-toggle="tooltip" data-placement="top" title="Click this to toggle the stack options.">STACKNAME</a></li>
<li id="presentation11-UUID" role="presentation"><a id="generate-button" class="btn btn-danger" onclick="delete_stack('UUID')" style="float:right";>Delete</a></li>
</ul>

</center>

<div class="tab-content" style="" id="contentPane-UUID">
    <div role="tabpanel" class="tab-pane fade" id="AutoScalingGroup-UUID">
        <div style="padding:15px;width:250px;">
            <form id="AutoScalingGroup-UUID">
                <label for="AutoScalingGroup-UUID">AutoScalingGroup</label>
                <div class="form-group"><label for="name">name</label>
                <input type="name" class="form-control" id="name-UUID" placeholder="ExampleASGConfig" data-toggle="tooltip" data-placement="top" title="name (str) &#x2013; Name of the auto scaling group to create.">
                </div>
                <div class="form-group">
                <label for="availability_zones-UUID">availability_zones</label>
                <select class="form-control" id="availability_zones-UUID" placeholder="us-west-2" data-toggle="tooltip" data-placement="top" title="availability_zones (list) &#x2013; List of availability zones (required).">
                <option value="us-east-1">us-east-1:US East (N. Virginia)</option>
                <option value="us-east-2">us-east-2:US East (Ohio)</option>
                <option value="us-west-1">us-west-1:US West (N. California)</option>
                <option value="us-west-2">us-west-2:US West (Oregon)</option>
                <option value="ca-central-1">ca-central-1:Canada (Central)</option>
                <option value="eu-west-1">eu-west-1:EU (Ireland)</option>
                <option value="eu-central-1">eu-central-1:EU (Frankfurt)</option>
                <option value="eu-west-2">eu-west-2:EU (London)</option>
                <option value="ap-northeast-1">ap-northeast-1:Asia Pacific (Tokyo)</option>
                <option value="ap-northeast-2">ap-northeast-2:Asia Pacific (Seoul)</option>
                <option value="ap-southeast-1">ap-southeast-1:Asia Pacific (Singapore)</option>
                <option value="ap-southeast-2">ap-southeast-2:Asia Pacific (Sydney)</option>
                <option value="ap-south-1">ap-south-1:Asia Pacific (Mumbai)</option>
                <option value="sa-east-1">sa-east-1:South America (São Paulo)</option>
                </select>
                </div>

                <div class="form-group">
                <label for="default_cooldown-UUID">default_cooldown</label>
                <input type="default_cooldown" class="form-control" id="default_cooldown-UUID" placeholder="300" data-toggle="tooltip" data-placement="top" title="default_cooldown (int) &#x2013; Number of seconds after a Scaling Activity completes before any further scaling activities can start."></div>

                <div class="form-group">
                <label for="desired_capacity-UUID">desired_capacity</label>
                <input type="desired_capacity" class="form-control" id="desired_capacity-UUID" placeholder="1" data-toggle="tooltip" data-placement="top" title="desired_capacity (int) &#x2013; The desired capacity for the group."></div>

                <div class="form-group">
                <label for="health_check_period-UUID">health_check_period</label>
                <input type="health_check_period" class="form-control" id="health_check_period-UUID" placeholder="300" data-toggle="tooltip" data-placement="top" title="health_check_period str &#x2013; Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health."></div>

                <div class="form-group">
                <label for="health_check_type-UUID">health_check_type</label>
                <input type="health_check_type" class="form-control" id="health_check_type-UUID" placeholder="EC2" data-toggle="tooltip" data-placement="top" title="health_check_type str &#x2013; The service you want the health status from, Amazon EC2 or Elastic Load Balancer."></div>

                <div class="form-group">
                <label for="launch_config-UUID">launch_config</label>
                <input type="launch_config" class="form-control" id="launch_config-UUID" placeholder="launch_config_name" data-toggle="tooltip" data-placement="top" title="launch_config str or LaunchConfiguration &#x2013; Name of launch configuration required."></div>

                <div class="form-group">
                <label for="load_balancers-UUID">load_balancers</label>
                <input type="load_balancers" class="form-control" id="load_balancers-UUID" placeholder="" data-toggle="tooltip" data-placement="top" title="load_balancers list &#x2013; List of load balancers."></div>

                <div class="form-group">
                <label for="max_size-UUID">max_size</label>
                <input type="max_size" class="form-control" id="max_size-UUID" placeholder="1" data-toggle="tooltip" data-placement="top" title="max_size (int) &#x2013; Maximum size of group required."></div>

                <div class="form-group">
                <label for="min_size-UUID">min_size</label>
                <input type="min_size" class="form-control" id="min_size-UUID" placeholder="1" data-toggle="tooltip" data-placement="top" title="min_size (int) &#x2013; Minimum size of group required."></div>

                <div class="form-group">
                <label for="placement_group-UUID">placement_group</label>
                <input type="placement_group" class="form-control" id="placement_group-UUID" placeholder="t1.micro" data-toggle="" data-placement="top" title="placement_group str &#x2013; Physical location of your cluster placement group created in Amazon EC2."></div>

                <div class="form-group">
                <label for="vpc_zone_identifier-UUID">vpc_zone_identifier</label>
                <input type="vpc_zone_identifier" class="form-control" id="vpc_zone_identifier-UUID" placeholder="sub-00000,sub-11111" data-toggle="tooltip" data-placement="top" title="vpc_zone_identifier str or list &#x2013; A comma-separated string or python list of the subnet identifiers of the Virtual Private Cloud."></div>

我不得不截斷一些HTML以適合該職位,但您明白了。

可以簡化您的collect函數,然后可以使用serializeArray或serialize將所有數據發布為json,例如:

var alldata = {};

$("form").each(function(i, form){
  var current_data = $(form).serializeArray();
  alldata[$(form).prop("id")]  = current_data;
});
alert(JSON.stringify(alldata));

$.ajax({
  //your parameters here: url, etc.
  url: 'save_stacks',
  type: 'post',
  dataType: 'json',
  data: alldata,
  success: function(response) {
    //handling code
  }
});

https://jsfiddle.net/1pLn4hw1/

您可能必須在后端調整您的處理代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM