如何获取PHP脚本以将数据提供给JQuery自动完成?

时间:2011-06-30 13:42:25

标签: php jquery json sqlite

我目前正在为JQuery Autocomplete提供以下数据

 var network_autocomplete=[
                "ActionScript",
                "AppleScript",
                "Asp",
                "BASIC",
                "C",
                "C++",
                "Clojure",
                "COBOL",
                "ColdFusion",
                "Erlang",
                "Fortran",
                "Groovy",
                "Haskell",
                "Java",
                "JavaScript",
                "Lisp",
                "Perl",
                "PHP",
                "Python",
                "Ruby",
                "Scala",
                "Scheme"
            ];

            $( "#network" ).autocomplete({
                source: network_autocomplete
            });

我需要修改它以从php页面检索结果数组。有人可以帮我修改这个,所以我可以在JavaScript中这样做吗?

network_autocomplete=data

目前,代码以这种方式从SQLite表中检索数据:

try {
    $db = new PDO('sqlite:/tmp/bacnet.db');
    $query = "SELECT net, name,  FROM network";

    foreach ($db->query($query) as $row) {
        $networks[] = array('net' => $row['net']);
    }

    echo json_encode($networks);
    return json_encode($networks);
} catch (PDOException $e) {
    echo json_encode(array('message' => 'Could not connect to the database'));
}

3 个答案:

答案 0 :(得分:1)

$networks[] = array('net' => $row['net']);更改为
$networks[] = $row['net']; 并且你不应该返回,除非这是一个函数(如果它是一个函数,为什么它有一个回声?)

答案 1 :(得分:0)

我需要的时候做的是将一些PHP直接放在javascript中,所以

foreach ($db->query($query) as $row) {
   $networks[] = '{ label: "blah", value: "' . $row['net'] . '" }';
}
$autocomplete = implode(",",$networks);

然后在脚本中你可以做到,

var network_autocomplete = [$autocomplete];
$( "#network" ).autocomplete({
    source: network_autocomplete
});

我希望这会有所帮助

答案 2 :(得分:0)

您可以执行以下操作:

<?php
$values = array("'foo'", "'bar'", "'baz'"); ?>

<script>
    $(function() {
        var network_autocomplete = [
          <?php echo join(",", $values) ?>
        ];
    ...
</script>