【问题标题】:html array of input elements created dynamically not properly interpreted in PHP Serverside动态创建的输入元素的 html 数组在 PHP Serverside 中未正确解释
【发布时间】:2020-07-30 02:32:58
【问题描述】:

我正在使用 DOM CreateElement() 动态创建 html 输入元素

function createHtmlElem( elName , attri ){

    var el = document.createElement(elName);
    for( var key in attri ){
        val = attri[key];
        el.setAttribute( key , val );
    }

    return el;
}

我想使用createHtmlElem( 'input' , {"name":"usernames[]"} ) 创建以下 html 元素,它可以工作,我的意思是它在页面上创建 HTML 元素。

<input type="text" name="usernames[]" />

问题出在服务器端。 我使用 jquery.serialize() 将表单序列化并发布, 在服务器端

期待

[usernames] => Array
        (
            [0] => andrew
            [1] => arul
        )

但我越来越喜欢

[usernames[]] => 'andrew'
[usernames[]] => 'arul'

我完全糊涂了,当您通过放置原始 html 并发布它来静态创建输入数组元素时,这是非常不可能的。

【问题讨论】:

    标签: javascript php html ajax serialization


    【解决方案1】:

    我创建了一个 post_processing 函数来处理接收到的数组。希望它对某人有用。

    /**
     * [create_array description]
     * Convert Array 
     * arr = [
     *     'username_1'=>'John Deo',
     *     'address_1'=>'wuhan',
     *     'pin_1'=>'560093',
     *     'username_2'=>'Dennis',
     *     'address_2'=>'Hubei',
     *     'pin_2'=>'605110'
     * ];
     *
     * arr = [
     *     [1] => [
     *         'username' => 'John Deo',
     *         'address'  => 'wuhan',
     *         'pin'      => '560093',
     *     ],
     *     [2] => [
     *         'username' => 'Napoleon',
     *         'address'  => 'Karnataka',
     *         'pin'      => '605110'
     *     ]
     * ]
     * @param  [type]  $inp    [description]
     * @param  integer $nitems [No of Set of items, for this eg nitems = 2]
     * @return [type]          [Rearrange array as required]
     */
    function rearrange_array( $input_arr , $nitems){
        //unset( $inp['donor_id'] );
        $n = count( $input_arr );
        $i = 0;
        //nitems is the number of items of objects or books
        for($i = 0; $i < $nitems ; $i++){
    
            $tmp = [];
            foreach( $input_arr as $k => $v ){
                $new_key = preg_replace("/_[0-9]/",'', $k);// getrid of the underscore and the number behind.
                $tmp[$new_key]=$input_arr[$new_key . '_' . $i];
            }
            $output_arr[$i]= $tmp;
        }
    
        return $output_arr;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 2014-01-23
      • 2011-09-26
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多