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

后端 未结 14 668
庸人自扰
庸人自扰 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;
    }
    
    0 讨论(0)
  • 2020-12-16 15:55

    Problem solved! Here is what i did.

    Inside PHP file to create rows of dynamic checkboxes,

      while ($row = mysqli_fetch_assoc($result))
      {
       extract($row);
       echo "<tr>";
       echo "<td bgcolor='#FFFFFF'><input name='books' type='checkbox' value='$book_id' />$book_id</td>";
       echo "<td bgcolor='#FFFFFF'>$book_name</td>";
       echo "</tr>";
      } // while
    

    I do not use JQuery $.post method anymore. I changed my code to the following

        var my_query_str = '';
    
    $("input[@type='checkbox'][@name='books']").each(
      function()
      {
        if(this.checked)
        {
               my_query_str += "&bookArray[]=" + this.value;
        }
      });
    
    
    $.ajax(
    {
        type: "POST",
        url: "saveBookList.php",
        data: "dummy_data=a" + my_query_str,
        success:
            function(responseData)
            {
                $("#save-result").empty().append(responseData);
            },
        error:
            function()
            {
                $("#save-result").append("An error occured during processing");
            }
    });
    

    Now, inside saveBookList.php page, value of $_POST['bookArray'] is an Array. Yey! Yey!

    I do hope and wish the $.post method of JQuery can support array data type as Prototype does. :)

    0 讨论(0)
  • 2020-12-16 16:01

    @Tomalak You can use the square brackets characters "[" and "]" within XHTML see http://www.w3.org/TR/xhtml1/dtds.html#dtdentry_xhtml1-transitional.dtd_input

    So this means that a name can contain many different characters legally within XHTML, although it doesn't make much sense to use slashes or brackets. PHP supports the use of array notation in form names, so you could be missing a trick if you don't use array notation in some instances.

    0 讨论(0)
  • 2020-12-16 16:05

    work correctly jquery =>

    var data = $('form').serialize();
                $.post(baseUrl+'/ajax.php',
                        {action:'saveData',data:data},
                        function( data ) {
                            alert(data);
                        });
    

    php =>

    parse_str($_POST['data'], $searcharray);
        echo ('<PRE>');print_r($searcharray);echo ('</PRE>');
    

    output =>

    [query] => 
    [search_type] => 0
    [motive_note] => 
    [id_state] => 1
    [sel_status] => Array
        (
            [8] => 0
            [7] => 1
        )
    

    and You can do whatever what you want like with array data, thanks to Aridane https://stackoverflow.com/questions/1792603

    0 讨论(0)
  • 2020-12-16 16:08

    jQuery 1.4

    var myform = $("book_form").serialize();
    
    decodeURIComponent(myform);
    
    0 讨论(0)
  • 2020-12-16 16:09

    it's not a problem with jQuery Post, it's with serialize you can do this:

        var my_query_str = ''; 
        $("input[@type='checkbox'][@name='books']").each( function() { 
           if(this.checked) { my_query_str += "&bookArray[]=" + this.value; } 
        }); 
       jQuery.post(
          "saveBookList.php",
          "dummy_data=a" + my_query_str ,
           function(responseData){   
              $("#save-result").empty().append(responseData); 
           }, 
           error: function() { 
                $("#save-result").append("An error occured during processing"); 
           }
       }); 
    

    but all you really have to do is replace '[' & ']' back to themselves after serializing them. because serialize(); changed them to their htmlencoded value!

    0 讨论(0)
提交回复
热议问题