通过ajax传递数组和其他数据

时间:2015-03-03 20:13:40

标签: javascript php arrays ajax codeigniter

这是我的javascript函数.... 但我的php控制器获取所有值但不是数组不确定为什么?需要帮忙..... 在此先感谢:)

function submitForm(){
    var id = $('#id').val(); 
    var supplier_id = $('#supplier_id').val();
    var description = $('#description').val();
    var numofpro = $('#numofpro').val();

    var product_id = new Array();
    for(var i=0;i<numofpro;i++){
        product_id[i] = $('#product_id'+(i+1)).val();               
    }
    var payment_mode = $('#payment_mode').val();
    //description = description.replace(new RegExp('\r?\n','g'), '<br />');     
    $.ajax({
            url: "<?= base_url(); ?>edit/save_purchase", //The url where the server req would we made.
            data: "id="+id+"&supplier_id="+supplier_id+"&description="+description+"&product_id="+product_id+"&payment_mode="+payment_mode,
            dataType: "html", //Return data type (what we expect).
            beforeSend:function(){
                //alert("asds");
            },
            success: function(data) {
                //alert("Edited");
                alert(data);

            }
        });
}

2 个答案:

答案 0 :(得分:0)

因为你传递一个字符串,而不是一个数组:)试试吧:

$.ajax({
        url: "<?= base_url(); ?>edit/save_purchase",
        type: "POST"
        data: {id : id, supplier_id : supplier_id, description : description, product_id : product_id, payment_mode : payment_mode},
        dataType: "json",
        beforeSend:function(){
           //alert("asds");
        },
        success: function(data) {
        //alert("Edited");
            alert(data);
         }
        });

在你的php中使用:

$arr = json_decode($_POST);
//some php code
//some $result;
// if $result arr then
echo json_encode($result);
// else 
echo json_encode(array('data' => $result))

希望这会有所帮助...

答案 1 :(得分:0)

您需要先将该数组转换为JS中的字符串。在发送之前,请执行以下操作:

JSON.stringify(product_id);

在PHP中收到它后,您需要解码它。

$decoded = json_decode($_POST['product_id'])