How to send serialize form data using JQuery if the input element is an array

后端 未结 14 671
庸人自扰
庸人自扰 2020-12-16 15:16

I have this piece of code in my PHP code:

while ($row = mysqli_fetch_assoc($result))
{
    extract($row);
    echo \"\";
    echo \"

        
14条回答
  •  失恋的感觉
    2020-12-16 15:54

    I have come up with a method that will, when the data is sent using post

    on the other side lets you access your elements using $_['post']['name']

    If it is an array (eg a multiple select) then on your server you can access it as an array again $_POST['myselect'][0]...

    Code: Function to serialize form data for post

    function serializePost(form) {
        var data = {};
        form = $(form).serializeArray();
        for (var i = form.length; i--;) {
            var name = form[i].name;
            var value = form[i].value;
            var index = name.indexOf('[]');
            if (index > -1) {
                name = name.substring(0, index);
                if (!(name in data)) {
                    data[name] = [];
                }
                data[name].push(value);
            }
            else
                data[name] = value;
        }
        return data;
    }
    

提交回复
热议问题