简体   繁体   中英

send a multidimensional array to php

I have an unknown number of inputs and i want to write them in a database. I tried some different ways but nothing worked. I dont know the number of the inputs, so i need something like a multidimensional array

javascript:

var temp=new Array();
    var obj;
    $("#mitarbFuktionen fieldset").each(function(){
        i=$(this).parent().children().index($(this));
        if ($(this).hasClass("New")){
          temp[0]='New';
          temp[1]=$("legend",this).text();
          //.....
          obj+=JSON.stringify(temp)
        }else if ($(this).hasClass("Remove")){
          temp[0]='Remove';
          temp[1]=$("legend",this).text();
          //.....
          obj=$.toJSON(temp);
        }

    })
    $.post("ajax/MitarbSave.php",{
        anrede:$('input[name="neuMitarbAnrede"]:checked').val(),
        titel:$('#neuMitarbTitel').val(),
        nation:$('#neuMitarbNat').val(),
        //.....
        'kom[]': obj
    }, function(data){
        alert(data);
    })

PHP:

$output= json_decode($_POST["kom"], true);
echo var_dump($output);

Just to provide an answer to my comment:

$(document).ready(function()
{
    var test = [];
        test.push('a');
        test.push('b');

    $.post('ajax/script.php',
    {
        Param : test
    }, 
    function(resp)
    {

    }, 'json');
});

jQuery will automatically convert an array when passed as an param to an Ajax request, to a multi-dimensional array.

You could also just build an object, an pass that:

var obj={};
$("#mitarbFuktionen fieldset").each(function(){
    var i=$(this).index();
    obj[i]={};
    obj[i][$(this).is(".New") ? 'New :' : 'Remove :'] = $("legend", this).text();
});

$.post("ajax/MitarbSave.php",{
    anrede:$('input[name="neuMitarbAnrede"]:checked').val(),
    titel:$('#neuMitarbTitel').val(),
    nation:$('#neuMitarbNat').val(),
    kom: obj
}, function(data){
    alert(data);
})​;​

just add the array to your input fields in HTML like:

<input type="text" name="neuMitarb[NUMBER][anrede]">
<input type="text" name="neuMitarb[NUMBER][titel]">
//...

So you let html create your array. Submitting your form like regular form submit with ajax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM