gpt4 book ai didi

javascript - 如何将php数据库值获取到javascript数组

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:24 25 4
gpt4 key购买 nike

您好,我正在使用 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
});
});

关于javascript - 如何将php数据库值获取到javascript数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32689450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com