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

Passing array and other data through ajax

这是我的 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);

            }
        });
}

因为你传递的是字符串,而不是数组 :) 试试看:

$.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))

希望这对您有所帮助...

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

JSON.stringify(product_id);

在PHP收到后,您需要对其进行解码。

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