简体   繁体   English

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

[英]Passing array and other data through ajax

This is my javascript function.... But my php controller getting all values but not the array not sure why ? 这是我的javascript函数....但我的php控制器获取所有值但不是数组不确定为什么? Need help..... Thanks in advance :) 需要帮助.....在此先感谢:)

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);

            }
        });
}

because you pass a string, not an array :) try it: 因为你传递一个字符串,而不是一个数组:)试试吧:

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

in you php use : 在你的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))

hope this helps... 希望这可以帮助...

You need to first turn that array into a string in JS. 您需要先将该数组转换为JS中的字符串。 Before sending it, do this: 在发送之前,请执行以下操作:

JSON.stringify(product_id);

Once you receive it in PHP, you need to decode it. 一旦你用PHP接收它,你需要解码它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM