dongzhang4301 2016-11-23 04:08
浏览 37
已采纳

如何在按钮单击时将Javascript数组传递给PHP数组?

I am having trouble passing a Javascript array to a PHP array on the same page when the submit button is pressed. I have seen discussion of JSON.stringify and json_encode on other posts, but I am not sure how to use those functions with my code.

JS:

    <script>
        var kegs = [];
        var textarea = document.getElementById("your_textarea");
        $("#kegId").on('keyup', function (e) {
            if (e.keyCode == 13) {
                kegs.push($(this).val());
                $("#kegId").val("");
                textarea.value = kegs.join("
");

                };
            });
    </script>

PHP:

if (!isset($_POST['btn-addkegs'])) {
//I want to set the Javascript array 'kegs' to a php variable here
  • 写回答

3条回答 默认 最新

  • dourong8495 2016-11-23 04:25
    关注

    Using Ajax will do it for you! I wrote this code that sends an array to PHP on the same page. Once you get the array in PHP you can do whatever you want with it :).Just copy and paste this file and called it index.php to see the result. This will totally help you!

    <?php
    
      $data = array();
       if(isset($_POST['myArray']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
       $data = 'You array is: ' . $_POST['myArray'];       
       echo json_encode($data);  
       die();      
       }
    ?>
     <html>
     <head>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    </head>
    
    <body>
    <div id = "random"></div>
    
    <script type = "text/javascript">
    
    $(document).ready(function() {
    
    var arr = [2,4,5,6,7];
    var myArray =  JSON.stringify(arr);
    
    $.ajax({
        url: "index.php",
        method: "POST",
        dataType: "json",
        data: {myArray: myArray},
        success: function (result) {
        alert("result: " + result);
        console.log(result);
      $("#random").html(result);
     }
    });
    
    });
    
    </script>
    
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 WPF动态创建页面内容
  • ¥15 如何对TBSS的结果进行统计学的分析已完成置换检验,如何在最终的TBSS输出结果提取除具体值及如何做进一步相关性分析
  • ¥15 SQL数据库操作问题
  • ¥100 关于lm339比较电路出现的问题
  • ¥15 Matlab安装yalmip和cplex功能安装失败
  • ¥15 加装宝马安卓中控改变开机画面
  • ¥15 STK安装问题问问大家,这种情况应该怎么办
  • ¥15 关于罗技鼠标宏lua文件的问题
  • ¥15 halcon ocr mlp 识别问题
  • ¥15 已知曲线满足正余弦函数,根据其峰值,还原出整条曲线