CakePhp使用Ajax提交 - 表单序列化不起作用

时间:2015-02-26 16:45:39

标签: javascript jquery ajax cakephp form-helpers

我试图使用ajax发送一个表格数据序列化的对象数组。当我发送序列化数据并将数组添加到ajax数据时出现问题。序列化的表单数据不会以正确的格式到达控制器。这是我的ajax:

$('body').on('submit','#RequestPakagesTempAddForm', function(e){

    if (!(productArray.length > 0) || jQuery.isEmptyObject(productArray) ) { 
        alert("Falta agregar productos");
        return false; 
    }

     form = $("#RequestPakagesTempAddForm").serialize();

     $.ajax({
        type: "POST",
        url: $(this).attr('action'),
        data: {
            'formData': form,
            'productArray': productArray
        },

        success: function(data){
            /*$('.modal').modal('hide');
            $(".success").fadeIn(500).delay(2000).fadeOut(500);*/
            $("#RequestPakagesTempAddForm")[0].reset();
            //Unterminated String constant fixed
            alert("hola");
        }

    });
    event.preventDefault();
    return false;  //stop the actual form post !important!

 });

productArray是我创建要在表单数据中发送的数组。控制器上的数组格式是正确的,但序列化的表单数据返回了一些奇怪的东西。以下是$this->request->data返回的内容:

    Array
(
    [formData] => _method=POST&data%5BRequestPakagesTemp%5D%5Bidentity_id%5D=10&data%5BAddress%5D%5Bexterior_number%5D=22&data%5BAddress%5D%5Binternal_number%5D=0&data%5BAddress%5D%5Bstreet%5D=a&data%5BAddress%5D%5Bsuburby%5D=a&data%5BRequestPakagesTemp%5D%5Btogether%5D=0&data%5BAddress%5D%5Bcountry_id%5D=1&data%5BAddress%5D%5Bstate_id%5D=19&data%5BAddress%5D%5Bcity_id%5D=993&data%5BRequestPakagesTemp%5D%5Bproducts_array%5D=
    [productArray] => Array
        (
            [0] => Array
                (
                    [product_name] => a
                    [product_number] => a
                    [category_name] => a
                    [brand_name] => a
                    [quantity] => a
                    [description] => a
                )

        )

)

我希望将表单数据作为我发送的数组发送。我的猜测是我在串行化ajax中的数据时搞砸了。感谢您的帮助:D

我提交的表单就是这个

<?php
                echo "<div class='row'>";
                echo "<div class='col-lg-4'>";
                echo '<div class="styled-select">';
                echo $this->Form->input('identity_id', array('empty' => 'Elige la Identidad', 'label' => false, 'placeholder' => 'Identidad', 'class' => 'txtBoxRegister'));
                echo '</div>';
                echo "</div>";
                echo "<div class='col-lg-4'>";
                echo $this->Form->input('Address.exterior_number', array( 'label' => false, 'placeholder' => 'Numero Exterior', 'class' => 'txtBoxRegister'));
                echo "</div>";
                echo "<div class='col-lg-4'>";
                echo $this->Form->input('Address.internal_number', array( 'label' => false, 'required' => false, 'placeholder' => 'Número Interior', 'class' => 'txtBoxRegister'));
                echo "</div>";
                echo "</div>";
                echo "<div class='row'>";
                echo "<div class='col-lg-4'>";
                echo $this->Form->input('Address.street', array( 'label' => false, 'placeholder' => 'Calle', 'class' => 'txtBoxRegister'));
                echo "</div>";
                echo "<div class='col-lg-4'>";
                echo $this->Form->input('Address.suburby', array( 'label' => false, 'placeholder' => 'Colonia', 'class' => 'txtBoxRegister'));
                echo "</div>";
                echo "<div class='col-lg-4'>";
                echo "<div data-toggle='tooltip' data-placement='right' title='Tooltip on right'>";
                echo $this->Form->input('together', array('label' => 'Todo Junto', 'class' => 'squaredTwo'));
                echo "</div>";
                echo "</div>";
                echo "</div>";
                echo "<div class='row'>";
                    echo "<div class='col-lg-4'>";
                        echo '<div class="styled-select">';
                        echo $this->Form->input('Address.country_id', array('required' => true, 'empty' => '', 'label' => false, 'class' => 'txtBoxRegister'));
                        echo '</div>';
                    echo "</div>";
                    echo "<div class='col-lg-4'>";
                        echo '<div class="styled-select">';
                        echo $this->Form->input('Address.state_id', array('required' => true, 'empty' => '', 'label' => false, 'class' => 'txtBoxRegister'));
                        echo '</div>';
                    echo "</div>";
                    echo "<div class='col-lg-4'>";
                        echo '<div class="styled-select">';
                        echo $this->Form->input('Address.city_id', array('required' => true, 'empty' => '', 'label' => false, 'class' => 'txtBoxRegister'));
                        echo '</div>';
                    echo "</div>";
                echo "</div>";
                echo $this->Form->input('products_array', array('type' => 'hidden', 'id' => 'product_array'));

            ?>

productArray是一个表单,每次提交时我都会向productArray变量添加一个元素(Object)。这是表格:

<?php
            echo '<div class="row">';
                echo '<div class="col-lg-12" style = "text-align:center;">';
                    echo $this->Form->input('product_name', array( 'label' => false,'required' => true, 'placeholder' => 'Nombre del Producto', 'class' => 'txtBoxRegister'));
                    echo $this->Form->input('product_number', array( 'label' => false, 'required' => false, 'placeholder' => 'Numero del Producto', 'class' => 'txtBoxRegister'));
                    echo $this->Form->input('brand_name', array( 'label' => false, 'required' => true, 'placeholder' => 'Nombre de la Marca', 'class' => 'txtBoxRegister'));
                    echo $this->Form->input('category_name', array( 'label' => false, 'required' => true, 'placeholder' => 'Nombre de la Cateogria', 'class' => 'txtBoxRegister'));
                    echo $this->Form->input('quantity', array( 'label' => false, 'required' => true, 'placeholder' => 'Cantidad del Producto (ejemp. 17 gramos)', 'class' => 'txtBoxRegister', 'id' => 'product_quantity'));
                    echo $this->Form->input('description', array( 'label' => false, 'required' => true, 'placeholder' => 'Descripción', 'class' => 'txtBoxRegister', 'type' => 'textarea', 'style' => 'height: 150px;', 'id' => 'product_description'));
                echo '</div>';
            echo '</div>';
        ?>

这里是我将元素添加到数组的js。

$("#productForm").submit(function( event ) {
    //console.log(productArray);
    $('#productBodyTable').append('<tr class="productRow" id="' + $("#product_number").val() +'"> <td class="countId">' + count + '</td> <td>' + $("#product_name").val() + '/' + $("#product_number").val() +'</td> <td>' + $("#brand_name").val() + '</td> <td>' + $("#product_description").val() + '</td> <td>' + $("#product_quantity").val() + '</td> <td> <button type="button" class="btn btn-danger delProduct" id="' + $("#product_number").val() + '" value = "' + countP + '"> <b>-</b> </button> </td> </tr>');
    event.preventDefault();
    var product = { 'product_name': $("#product_name").val(), 'product_number': $("#product_number").val(), 'category_name': $("#category_name").val(), brand_name: $("#brand_name").val(), 'quantity': $("#product_quantity").val(), description: $("#product_description").val()};
    //console.log(product);
    productArray[countP] = product;
    //console.log(productArray);
    count = count + 1;
    countP = countP + 1;    
    $('#createIdentityModal').modal('hide');
    $('#createIdentityModal').find('form')[0].reset();

    $(".delProduct").click(function() {

        delete productArray[$(this).val()];

        $(this).parent().parent().remove();
        //console.log(productArray);

        restartCounter();
    });
});

顺便说一句,productArray是一个全球价值。

2 个答案:

答案 0 :(得分:1)

好的,我发现了序列化表单的问题。该方法正在做它想要做的事情。我只是没有在控制器端给它格式化。所以我发现在控制器中使用它:

$FormOne = $this->request->data['formData'];
$FormOneValues = array();
parse_str($FormOne, $FormOneValues);

$this->request->data['formData'] = $FormOneValues['data'];

我可以将我想要的格式提供给我得到的表单数据。我不明白序列化方法的作用。通过使用parse_str(),我可以使用我需要的格式添加表单数据。如果从视图方面有一种更简单的方法,我仍然希望听到它。我还在学习使用CakePhp。希望这可以帮助将来的某个人。

答案 1 :(得分:1)

好吧,用parse_str()函数解析服务器端的数据不是最好的方法。您所要做的就是将表单数据不是作为字符串传递,而是作为序列化数组传递。您可以使用此方法执行此操作:http://api.jquery.com/serializearray/

所以在你的情况下,只需改变:

form = $("#RequestPakagesTempAddForm").serialize();

form = $("#RequestPakagesTempAddForm").serializeArray();

或者如果你想获得键值对,最后没有数字索引:

 var form = { };
 $.each($("#RequestPakagesTempAddForm").serializeArray(),function() {
      form[this.name] = this.value;
 });