【问题标题】:Passing array and other data through ajax通过ajax传递数组和其他数据
【发布时间】:2015-03-03 20:13:40
【问题描述】:

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

            }
        });
}

【问题讨论】:

  • 试试data: {id:id, supplier_id:supplier_id, description:description, product_id:product_id, payment_mode:payment_mode},而不是你的长字符串。应该是这样设置的。
  • 它解决了我的问题...thnx :)

标签: javascript php arrays ajax codeigniter


【解决方案1】:

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

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

希望这会有所帮助...

【讨论】:

    【解决方案2】:

    你需要先在 JS 中把这个数组变成一个字符串。在发送之前,请执行以下操作:

    JSON.stringify(product_id);
    

    一旦你在 PHP 中收到它,你需要对其进行解码。

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

    【讨论】:

      猜你喜欢
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 2017-12-01
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多