使用 JSON 从 JavaScript/jQuery 中的 PHP 获取数组,然后对其进行操作


Getting an array from PHP in JavaScript/jQuery using JSON, and manipulating it afterwards?

所以我正处于一个相当棘手的问题之中。我快要接近了——太近了!- 解决它,但并不完全存在。我见过很多例子,但没有一个能完全满足我的需求。

在 php 页面 myreqpdo.php 上,我从 MySQL 表中恢复一些数据行并将它们存储在二维数组中。在我的页面索引.php上,我需要通过 JavaScript 访问这个数组并在将其发送到我需要填充的内容之前稍微使用它。

这是myreqpdo.php:

$locWanted = $_POST['searchTerm'];
echo json_encode(getVillesCPs($locWanted));
function getVillesCPs ($searchTerm) {
    // code to access DB here
    return $resultats;
}

我使用 jQuery 找到了这个示例,但它适用于一个只想将列表直接插入代码而无需任何进一步操作的实例:

<html>
<head>
        <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>
        <!-- this UL will be populated with the data from the php array -->
        <ul></ul>
        <script type='text/javascript'>
        $(document).ready(function(){
                /* call the php that has the php array which is json_encoded */
                $.getJSON('json_encoded_array.php', function(data) {
                        /* data will hold the php array as a javascript object */
                        $.each(data, function(key, val) {
                                $('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + ' ' + val.age + '</li>');
                        });
                });
        });
        </script>
</body>
</html>

这对我不起作用,因为这个函数是基于搜索参数触发的。我需要类似于以下伪代码的东西:

<script>
    var myArray = {code to recover PHP array};
    // manipulations for myArray here, using data to fill values of items on page
</script>

我一直认为答案就在我眼皮底下,但我真的没有看到我想要的例子!有什么想法吗?

你不需要jQuery在你的javascript代码中插入一个来自PHP的数组,只需直接插入到需要的地方:

<script>
    var myArray = <?php echo json_encode(getVillesCPs($locWanted)); ?>;
    // manipulations for myArray here, using data to fill values of items on page
</script>

请注意,在此代码之前,您必须在 PHP 代码中为 $locWanted var 设置一个值,否则将使用空参数调用其他getVillesCPs


编辑:由于您的getVillesCPs是在另一个PHP文件中定义的,因此在调用它之前将其包含在主页中(假设您的主页是PHP文件):
<?php 
//including the PHP file containing the function
include 'myreqpdo.php';
//setting a value for $locWanted, used then in the rest of the page
$locWanted = 'Paris';
?>
<script>
    var myArray = <?php echo json_encode(getVillesCPs($locWanted)); ?>;
    // manipulations for myArray here, using data to fill values of items on page
</script>

并删除 myreqpdo.php 中的前 2 行代码,您不想在调用函数之前echo任何内容。