如何将 PHP 数组传递给 jQuery AJAX $.post

How to pass a PHP Array into jQuery AJAX $.post

Objective:
我有 php array 变量,我需要将这个数组($key$value)放入 jQuery AJAX $.post,然后发送它转到另一个 php(next.php) 页。

PHP 数组变量:

$issue['key01']='value01';  
$issue['key02']='value02';

jQuery Ajax:

<head>
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function() {
    $("#ButtonCreate").click(function() {
    $.post("next.php",
                {
                ?????????
                },        
    function(data, status)  {
            document.getElementById("ResultBack").innerHTML = data;
    });
});
});
</script>
</head>


<body>
    <button id="ButtonCreate">Proceed DB Initialize</button>
    <p id="ResultBack"></p>
</body>

Problem and my finding:
The code has no issue if I directly use the string name and value. If I use non-array php variable, I still know how to do it. But I don't have any idea on how to pass a php array variable.

我能想到用php foreach命令来运行遍历数组,但是真的很头疼。甚至还有一个 if 命令来决定在变量之间放置逗号 (,)。结论是一条漫长而愚蠢的路。

请指教 谢谢。

您可以使用 json_encode 来创建一个有效的 javascript 对象

$("#ButtonCreate").click(function() {
    $.post("next.php", <?php echo json_encode($issue); ?>,        
    function(data, status)  {
        document.getElementById("ResultBack").innerHTML = data;
    });
});

如果您想通过 ajax 发送 2 个数组,您可以像这样创建一个新数组:

<?php echo json_encode(array(
    'issues' => $issue,
    'foo' => $foo,
)); ?>
  $(document).ready(function(){

  $("#id_form").on("submit", function() {
    if(window.localStorage!==undefined) {
        var JSvar = $(this).serialize();
      $.ajax({
        url: "sql_update_bill.php",
        type: "POST",
        data: Jsvar,
 
       });
      };
    });
  });