簡體   English   中英

使用 AJAX 將 Javascript 數組傳遞給 PHP

[英]pass Javascript array to PHP using AJAX

我必須將 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 文件中刪除該特定行。

根據您編輯的關於您的代碼的幾條注釋:第一 - 將所有 javascript function 放在一個地方,讓我們說就在結束 body 標簽之前 - 像這樣:

<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% 上運行

暫無
暫無

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

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