您好,我正在使用 jquery 自动完成插件。我有一些 php 检索的数据库值,我想在自动完成插件中使用这些值。为此,我想将 php 值获取到 javascript 数组。我该怎么做?
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
];
$( "#category" ).autocomplete({
source: availableTags
});
});
PHP:
<?php
require_once "config.php";
$q = strtolower($_GET["q"]);
if (!$q) return;
$sql = "select distinct(category) from completer";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
$fname = $rs['category'];
echo "$fname"
}
?>
好吧,如果你在 php 变量中有数据存储,那么你可以像这样将这些值添加到 javascript 变量中,不需要 ajax 的东西:
假设您在 php 变量中有如下值:
$myPhpVar = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
];
那么在你的js部分应该是:
$(function() {
var availableTags = [];
// start here - populate the data from php variable
<?php foreach($myPhpVar as $key => $val) {?>
availableTags.push('<?php echo $val;?>'); // push data into js variable
<?php }?>
// end here
$( "#category" ).autocomplete({
source: availableTags
});
});
我是一名优秀的程序员,十分优秀!