使用AJAX将JavaScript数组传递到PHP

4

我需要将Javascript数组变量传递到PHP中, 因此在同一页中同时有PHP和Javascript代码。

当我在isset($ _POST ['kvcArray'])中输入控制台 -->它不会打印。猜测出了一些问题。有人可以帮忙吗?

    body {
        color: #566787;
        background: #f5f5f5;
        font-family: 'Varela Round', sans-serif;
        font-size: 13px;
    }
    .table-wrapper {
            background: #fff;
            padding: 20px 25px;
            margin: 30px 0;
            border-radius:1px;
            box-shadow: 0 1px 1px rgba(0, 0, 0, 0.247);
    }
    .table-title {        
        padding-bottom: 15px;
        background: linear-gradient(40deg, #2096ff, #05ffa3) !important;
        color: #fff;
        padding: 16px 30px;
        margin: -20px -25px 10px;
        border-radius: 1px 1px 0 0;
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.247);
    }
    .table-title h2 {
        margin: 5px 0 0;
        font-size: 24px;
    }
    .table-title .btn-group {
        float: right;
    }
    .table-title .btn {
        color: #fff;
        float: right;
        font-size: 13px;
        border: none;
        min-width: 50px;
        border-radius: 1px;
        border: none;
        outline: none !important;
        margin-left: 10px;
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.247);
    }
    .table-title .btn i {
        float: left;
        font-size: 21px;
        margin-right: 5px;
    }
    .table-title .btn span {
        float: left;
        margin-top: 2px;
    }
    table.table tr th, table.table tr td {
        border-color: #e9e9e9;
        padding: 12px 15px;
        vertical-align: middle;
    }
    table.table tr th:first-child {
        width: 60px;
    }
    table.table tr th:last-child {
        width: 100px;
    }
    table.table-striped tbody tr:nth-of-type(odd) {
        background-color: #fcfcfc;
    }
    table.table-striped.table-hover tbody tr:hover {
        background: #f5f5f5;
    }
    table.table th i {
        font-size: 13px;
        margin: 0 5px;
        cursor: pointer;
    } 
    table.table td:last-child i {
        opacity: 0.9;
        font-size: 22px;
        margin: 0 5px;
    }
    table.table td a {
        font-weight: bold;
        color: #566787;
        display: inline-block;
        text-decoration: none;
        outline: none !important;
    }
    table.table td a:hover {
        color: #2196F3;
    }
    table.table td a.edit {
        color: #FFC107;
    }
    table.table td a.delete {
        color: #F44336;
    }
    table.table td i {
        font-size: 19px;
    }
    table.table .avatar {
        border-radius: 1px;
        vertical-align: middle;
        margin-right: 10px;
    }
    .pagination {
        float: right;
        margin: 0 0 5px;
    }
    .pagination li a {
        border: none;
        font-size: 13px;
        min-width: 30px;
        min-height: 30px;
        color: #999;
        margin: 0 2px;
        line-height: 30px;
        border-radius: 1px !important;
        text-align: center;
        padding: 0 6px;
    }
        .pagination li a:hover {
            color: #666;
        } 
        .pagination li.active a, .pagination li.active a.page-link {
            background: #03A9F4;
        }
        .pagination li.active a:hover {        
            background: #0397d6;
        }
    .pagination li.disabled i {
            color: #ccc;
        }
        .pagination li i {
            font-size: 16px;
            padding-top: 6px
        }
        .hint-text {
            float: left;
            margin-top: 10px;
            font-size: 13px;
        }    
    /* Custom checkbox */
    .custom-checkbox {
    position: relative;
    }
    .custom-checkbox input[type="checkbox"] {    
    opacity: 0;
    position: absolute;
    margin: 5px 0 0 3px;
    z-index: 9;
    }
    .custom-checkbox label:before{
    width: 18px;
    height: 18px;
    }
    .custom-checkbox label:before {
    content: '';
    margin-right: 10px;
    display: inline-block;
    vertical-align: text-top;
    background: white;
    border: 1px solid #bbb;
    border-radius: 1px;
    box-sizing: border-box;
    z-index: 2;
    }
    .custom-checkbox input[type="checkbox"]:checked + label:after {
    content: '';
    position: absolute;
    left: 6px;
    top: 3px;
    width: 6px;
    height: 11px;
    border: solid #000;
    border-width: 0 3px 3px 0;
    transform: inherit;
    z-index: 3;
    transform: rotateZ(45deg);
    }
    .custom-checkbox input[type="checkbox"]:checked + label:before {
    border-color: #03A9F4;
    background: #03A9F4;
    }
    .custom-checkbox input[type="checkbox"]:checked + label:after {
    border-color: #fff;
    }
    .custom-checkbox input[type="checkbox"]:disabled + label:before {
    color: #b8b8b8;
    cursor: auto;
    box-shadow: none;
    background: #ddd;
    }
    /* Modal styles */
    .modal .modal-dialog {
    max-width: 400px;
    }
    .modal .modal-header, .modal .modal-body, .modal .modal-footer {
    padding: 20px 30px;
    }
    .modal .modal-content {
    border-radius: 1px;
    }
    .modal .modal-footer {
    background: #ecf0f1;
    border-radius: 0 0 1px 1px;
    }
        .modal .modal-title {
            display: inline-block;
        }
    .modal .form-control {
    border-radius: 1px;
    box-shadow: none;
    border-color: #dddddd;
    }
    .modal textarea.form-control {
    resize: vertical;
    }
    .modal .btn {
    border-radius: 1px;
    min-width: 100px;
    } 
    .modal form label {
    font-weight: normal;
    } 
<script type="text/javascript">
$(document).ready(function(){
    // Activate tooltip
    $('[data-toggle="tooltip"]').tooltip();
    
    // Select/Deselect checkboxes
    var checkbox = $('table tbody input[type="checkbox"]');
    $("#selectAll").click(function(){
        if(this.checked){
            checkbox.each(function(){
            this.checked = true;                        
            });
        }else{
            checkbox.each(function(){
                this.checked = false;                        
            });
        } 
    });
    checkbox.click(function(){
        if(!this.checked){
            $("#selectAll").prop("checked", false);
        }
    });
});
</script>
</head>
<body>
    <div class="container">
        <div class="table-wrapper">
            <div class="table-title">
                <div class="row">
                    <div class="col-sm-6">
      <h2>Manage <b>Instances</b></h2>
     </div>
     <div class="col-sm-6">
      <a href="#addEmployeeModal" class="btn btn-success" data-toggle="modal"><i class="material-icons">&#xE147;</i> <span>Add New Employee</span></a>
      <!-- <button id="Delete" onclick="Deleteall();" class="btn btn-danger" data-toggle="modal"><i class="material-icons">&#xE872;</i> <span>DELETe Existing User</span></a>       -->
       <input type="submit" class="button1" name="insert" value="insert" /> 
    </div>
</div>
</div>
    <div align="center">
    <form method="post" id="theform">
     <button type="button" name="load_data" id="load_data" class="btn btn-info">Load Data</button>
     </form>
    </div>
    <br />
    <div id="employee_table">
    </div>
   </div>
  </div>

   <div id="addEmployeeModal" class="modal fade">
  <div class="modal-dialog">
   <div class="modal-content">
   <form method="POST" action="Index.php">  
     <div class="modal-header">      
      <h4 class="modal-title">Add Employee</h4>
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
     </div>
     <div class="modal-body">     
      <div class="form-group">
      <label>Customer Name</label>
       <input type="text" class="form-control"  name="CName" required>
      </div>
      <div class="form-group">
      <label>Environment</label>
       <input type="text" class="form-control" name="Environment" required>
      </div>
      <div class="form-group">
      <label>URL Value</label>
       <textarea class="form-control" name = "URLValue"required></textarea>
      </div>   
     <div class="modal-footer">
      <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
      <input type="submit" name="submit" class="btn btn-info" value="Insert">
     </div>
    </form>
   </div>
  </div>
 </div>
</div>

 </body>
<script type="text/javascript">
    $( document ).ready(function() {
        $( ".button1" ).click(function() {
            var val = [];
            $("input:checked").each(function (index,value) {
                    val[index] = this.value;
            });

            var myJSONText = JSON.stringify(val);
            $.ajax({
                data: {"myJSONText": myJSONText},
                type: 'POST',
                success: function(response) {
                    alert(response);
                }
            });
        });
    });
</script>

<?php
    if (isset($_POST['myJSONText'])) {
        echo "<script>console.log('Debug Objects' );</script>";
        echo "<pre>";
        var_dump(json_decode($_POST['kvcArray'], true));
        echo "</pre>";
        die();
    }
?>

 <?php   
  if(isset($_POST['submit'])){
       //index.php
            $file_open = fopen("FILES/employee.csv", "a");
            $no_rows = count(file("FILES/employee.csv"));
            if($no_rows > 1){
                $no_rows = ($no_rows - 1) + 1;
            }
            $form_data = array(
            'CustomerName'  => $_POST['CName'],
            'Environment'  =>  $_POST['Environment'],
            'URLValue'  =>  $_POST['URLValue']
            );

            fputcsv($file_open, $form_data);
    }

 ?>


</html>

<script>
$(document).ready(function(){
 $('#load_data').click(function(){
  $.ajax({
   url:"FILES/employee.csv",
   dataType:"text",
   success:function(data)
   {
    var employee_data = data.split(/\r?\n|\r/);
    var table_data = ' <table class="table table-striped table-hover"><thead> <tr><th><span class="custom-checkbox"><input type="checkbox" id="selectAll"><label for="selectAll"></label></span></th>';
    table_data += '<tr><th></th>';
    for(var count = 0; count<employee_data.length; count++)
    {
     var cell_data = employee_data[count].split(",");
    //  table_data += '<tr>';
     for(var cell_count=0; cell_count<cell_data.length; cell_count++)
     {
      if(count === 0)
      {
       table_data += '<th>'+cell_data[cell_count]+'</th>';
       if(cell_count == 4){
           table_data += '<th></th><th></th>';
       }
      }
      else
      {
          if(cell_count === 0 ){
            table_data +='<tr><td><span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox"'+count+'" name="options[]" value="'+count+'"><label for="checkbox1"></label></span></td>';
            table_data += '<td>'+cell_data[cell_count]+'</td>';
         }else{
             table_data += '<td>'+cell_data[cell_count]+'</td>';
          }
      }
     }
         table_data += '</tr>';
    }
    table_data += '</table>';
    $('#employee_table').html(table_data);
   }
  });
 });
 
});
</script>

以上提供了整个代码,添加实例很好用,但唯一的问题是当我点击删除时,应该将所选的所有复选框值传递给php,以便我可以从csv文件中删除该特定行。


但是在 PHP 中,我无法获取数组值。为什么?print_r 显示了什么? - cojack
@NiranjanaNeeranj 尝试不使用 json_decode 打印它 - cojack
抱歉,我尝试过了,但它没有起作用。@RandyCasburn - Niranjana Neeranj
甚至那也不起作用 @WesleySmith - Niranjana Neeranj
猜测在这个 @c 中没有发布数据(如果(isset($_POST['myJSArray'])){ })。 - Niranjana Neeranj
显示剩余4条评论
1个回答

1
根据您的编辑,关于您的代码有几点需要注意: 1. 将所有JavaScript函数放在一个地方,比如在 closing body tag 之前 - 如下所示:
<script>
    $(document).ready(function(){
      // all your function here ! in 1 place
    });
</script>
</body>
</html>

第二点 - 不是很重要,但仍然建议将所有的PHP代码移到文件顶部:

<?php
  // all the php here
?>
<!DOCTYPE html>
<html>
<head>
...
...

据我所知,您正在向与复选框表单相同的页面发出请求。因此,您可以像这样做:

<?php
    if (isset($_POST['kvcArray'])) {
        echo "<pre>";
        echo "<b>".__FILE__."</b><br/>";
        var_dump(json_decode($_POST['kvcArray'], true));
        echo "</pre>";
        die();
    }
?>

<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox1" name="options[]" value="1"><label for="checkbox1"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox2" name="options[]" value="2"><label for="checkbox2"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox3" name="options[]" value="3"><label for="checkbox3"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox4" name="options[]" value="4"><label for="checkbox4"></label></span><br />
<input type="submit" class="button" name="insert" value="insert" />

请注意,我已编辑了您的JS代码,修改了您构建数组的方式,并且在向同一页面发布时不需要在ajax中使用"url"!
<script type="text/javascript">
    $( document ).ready(function() {
        $( ".button" ).click(function() {

            var val = [];
            $("input:checked").each(function (index,value) {
                    val[index] = this.value;
            });

            var myJSONText = JSON.stringify(val);
            $.ajax({
                data: {'kvcArray': myJSONText},
                url: 'index.php',
                type: 'POST',
                success: function(result) {
                    //alert("Success");
                }
            });
        });
    });
</script>

这段代码已经过测试,在100%情况下正常工作。


抱歉,但在我的代码中它没有起作用。有没有办法我可以传递整个代码? - Niranjana Neeranj
我尝试了单独运行它,没有将我的代码集成进去。但是它既没有给我错误,也没有输出值,当我在成功函数中加入alert(data)时,它会将整个代码显示出来。 - Niranjana Neeranj
你能发布你整个的代码吗?从index.php开始的所有代码。 - Angel Deykov
很抱歉,我无法发布翻译后的文本。请提供原始英文文本以便我进行翻译。 - Niranjana Neeranj
你的意思是它不允许你吗?只需编辑你的问题并将index.php文件中的所有代码放入即可... - Angel Deykov
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接