doubi1931 2016-12-11 08:05
浏览 60

将多个数组的ajax数据发布到php

I've successfully posted a single serialized array, but I can't figure out how to post more than one array in an AJAX post. Here is my code:

HTML

<td><input type="text" name='item_name[]' id="item_name" class="form-control" autocomplete="off"></td>
<td><input type="number" name='quantity[]' id="quantity" class="form-control" autocomplete="off"></td>

jquery

$("#create_order").click(function(){  

    var item_name = $('[name="item_name[]"]').serialize();
    var quantity = $('[name="quantity[]"]').serialize();

    $.ajax({

        url: "includes/ajax_new_order.php",
        data: {item_name:item_name, quantity:quantity},

        type: "POST",

        success:function(data){ 

            $("#editModal").modal('hide'); 

            $('#create_order').html('<span class="glyphicon glyphicon-ok" aria-hidden="true"></span> Save');
        }
    });
});

PHP

<?php require("../init.php");

    $item_name = $_POST['item_name'];
    $quantity = $_POST['quantity'];

    foreach (array_combine($item_name, $quantity) as $key1 => $key2) {

      $query = $database->query("INSERT INTO order_tb(item,quantity) VALUES('$key1','$key2') ");
      if ($query) {
        echo "<p>Success</p>";
      }
      else { 
        echo "<p>Failed</p>"; 
      } 
    }
?>

One array works fine, however when I try to add a second array quantity to the data: field, it doesn't work.

  • 写回答

1条回答 默认 最新

  • doupishan3309 2016-12-18 09:21
    关注

    You can use map function instead of serialize function. Here is a sample code. Just replaced your jquery code by this bellow sample code.

    $("#create_order").click(function(){  
    
        //var item_name = $('[name="item_name[]"]').serialize();
        //var quantity = $('[name="quantity[]"]').serialize();
    
        var item_name =$('[name="item_name[]"]').map(function(){return $(this).val();}).get();
        var quantity = $('[name="quantity[]"]').map(function(){return $(this).val();}).get();
    
    
        $.ajax({
    
            url: "includes/ajax_new_order.php",
            data: {item_name:item_name, quantity:quantity},
    
            type: "POST",
    
            success:function(data){ 
    
                $("#editModal").modal('hide'); 
    
                $('#create_order').html('<span class="glyphicon glyphicon-ok" aria-hidden="true"></span> Save');
            }
        });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)