在JQuery中从动态表单创建多维数组

时间:2015-09-17 17:45:42

标签: javascript php jquery arrays multidimensional-array

我试图从输入中捕获值并将它们放在JQuery对象中,而不是必须处理PHP索引。

这是表格

<form name="second_form" id="second_form" action="#" method="POST">         
    <a href="#" id="AddChampion" onclick="return false;">Add Champion</a>
        <div id="ChampionInput">
        </div>
        <br><br>
        <input id="obj" type="hidden" name="obj">
        <input type="submit" name="submit">
    </form>

我尝试用来重新创建数组的脚本:

$("#second_form").submit(function(event) {   
    var object = [];        
    $('.Champion').each(function() {
        var champion = {
            'name': $(this).find(".ChampionInput").val(),
            'change': $(this).find("input:radio:checked").val(),
            'General_Description': [],
            'General_Change':[]
        };
        $(this).find('.GeneralChange').each(function() {            champion.General_Description.push($(this).children(".GeneralChangeDescription").val());
            champion.General_Change.push($(this).children(".General_Change").val());
        });         
        object.push(champion);
    });
    object = JSON.stringify(object);
    $('#obj').val(object); //Sending object to hidden input   
});

以下是我用来创建这个PHP数组的方法,当我在创建表单时删除一些输入时会混淆索引

 foreach($_POST['champion'] as $champion){
                if(isset($_POST['Release'][$ChampionNumber])){
                    $_POST['Release'][$ChampionNumber]=='New' ? $champions[$champion]['New']=1 : $champions[$champion]['New']=0;

                    $_POST['Release'][$ChampionNumber]=='Rework' ? $champions[$champion]['Rework']=1 : $champions[$champion]['Rework']=0;

                }
                if(!empty($_POST['GeneralChangeDescription'][$ChampionNumber])){
                    foreach($_POST['GeneralChangeDescription'][$ChampionNumber] as $indexGeneral=>$GeneralChangeDescription){
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] =ucfirst(trim($GeneralChangeDescription));
                    if(substr($GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1], -1)!='.'){
                        $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1].'.';
                    }
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace('/\s\/\s/','/',$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/(\.?\d\/?%?)+/', '<strong>$0</strong>', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/\b\w+\.(jpg|png|gif)/', '', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);                   
                    $champions[$champion]['General']['Change'][] =  $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1];
                    $champions[$champion]['General']['Type'][] = $_POST['GeneralChange'][$ChampionNumber][$indexGeneral];

                    }
                }

                $ChampionNumber++;              
            }

删除冠军

$('div#ChampionInput').on('click', 'a.Remove',function(){
    var champion = $(this).closest('.Champion');
    var id = champion.data("id");
    var nextChampion = champion;

    while((nextChampion = nextChampion.next()).length != 0){

        nextChampion.attr("data-id",id++);
        nextChampion.children('.ChampionInput').attr('placeholder','Champion '+ id);

    }
    championNumber=id+1;
    championNumberArray=id;
    champion.remove();
});

删除更改

$('div#ChampionInput').on('click', 'a.RemoveGeneralChange',function(){
        $(this).closest('.GeneralChange').remove();
    });

以下是我的数组在PHP中的样子:http://i.imgur.com/rURnNTG.png我希望在通过表单中的隐藏输入发送JQuery对象并在PHP中获取它之后得到类似的数组。以下是我的JQuery对象现在的样子http://imgur.com/2r9iyKN,它甚至不是很接近。

这里也是表单创建的JSfiddle:jsfiddle.net/g50zd384 /

1 个答案:

答案 0 :(得分:0)

如果你真的需要那个数组,那么在发送表单后用PHP创建它:

$array;
for($i = 1; $i <= count($_POST['champion']); $i++) {
    $champion = $_POST['champion'][$i];
    $array[$champion]['General'] = $_POST['GeneralChangeDescription'][$i];
    $array[$champion]['Type'] = $_POST['GeneralChange'][$i];
    $array[$champion]['Release'] = $_POST['Release'][$i];
}

您的表单应使用以下名称创建:

championNumber = 1;
    championNumberArray = 0;
    $('a#AddChampion').on('click',function(){
        $('div#ChampionInput').append(
        '<div class="Champion">\
             <br>\
             <input type="text" class="ChampionInput" name="champion['+championNumber+']" placeholder="Champion '+championNumber+'">\
             <datalist id="champions"></datalist>\
             <input type="radio" name="Release['+championNumber+']" value="New">New\
             <input type="radio" name="Release['+championNumber+']" value="Rework">Rework\
             <input type="radio" name="Release['+championNumber+']" value="None" checked>None\
             <a href="#" class="AddGeneralChange" data-id="'+championNumber+'" onclick="return false;">Add General Change</a>\
             <div class="GeneralChanges">\
             </div>\
             <br>\
         <div>');
        championNumber++;
    });
    $('div#ChampionInput').on('click','a.AddGeneralChange', function(){
        var id = $(this).data('id');
        $(this).siblings('.GeneralChanges').append(
           '<div class="GeneralChange">\
                <textarea type="text" size="20" rows="3" cols="50" maxlength="500" class="GeneralChangeDescription" name="GeneralChangeDescription['+id+'][]" placeholder="Enter General Change Description"></textarea>\
                <select class="General_Change" name="GeneralChange['+id+'][]">\
                   <option value="buff">Buff</option>\
                   <option value="nerf">Nerf</option>\
                   <option value="new">New</option>\
                   <option value="change">Change</option>\
                   <option value="bugfix">Bugfix</option>\
                </select>\
            </div>');
    });

重要的是,您以这种方式命名输入! ..不是最好的方法,但比以隐藏的输入形式发送json数据更好。我希望这可以帮到你。