簡體   English   中英

通過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'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM